mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

pvarga88
12.20.2020 2b5790588e1de6415985a05167cdb15512cce290
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2006-2008 Sun Microsystems, Inc.
 * Portions Copyright 2014-2016 ForgeRock AS.
 * Portions copyright 2015 Edan Idzerda
 */
package org.opends.server.util;
 
 
 
import static com.forgerock.opendj.cli.CommonArguments.*;
 
import static org.opends.messages.ToolMessages.*;
import static org.opends.messages.UtilityMessages.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.*;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
 
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.LocalizableMessageBuilder;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.server.core.DirectoryServer;
 
import com.forgerock.opendj.cli.ArgumentException;
import com.forgerock.opendj.cli.ArgumentParser;
import com.forgerock.opendj.cli.BooleanArgument;
import com.forgerock.opendj.cli.StringArgument;
 
 
 
/**
 * This class defines an e-mail message that may be sent to one or more
 * recipients via SMTP.  This is a wrapper around JavaMail to make this process
 * more convenient and fit better into the Directory Server framework.
 */
@org.opends.server.types.PublicAPI(
     stability=org.opends.server.types.StabilityLevel.VOLATILE,
     mayInstantiate=true,
     mayExtend=false,
     mayInvoke=true)
public final class EMailMessage
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
 
  /** The addresses of the recipients to whom this message should be sent. */
  private List<String> recipients;
 
  /** The set of attachments to include in this message. */
  private final List<MimeBodyPart> attachments;
 
  /** The MIME type for the message body. */
  private String bodyMIMEType;
 
  /** The address of the sender for this message. */
  private String sender;
 
  /** The subject for the mail message. */
  private String subject;
 
  /** The body for the mail message. */
  private LocalizableMessageBuilder body;
 
  /**
   * Creates a new e-mail message with the provided information.
   *
   * @param  sender      The address of the sender for the message.
   * @param  recipients  The addresses of the recipients for the message.
   * @param  subject     The subject to use for the message.
   */
  public EMailMessage(String sender, List<String> recipients,
                      String subject)
  {
    this.sender     = sender;
    this.recipients = recipients;
    this.subject    = subject;
 
    body         = new LocalizableMessageBuilder();
    attachments  = new LinkedList<>();
    bodyMIMEType = "text/plain";
  }
 
 
 
  /**
   * Retrieves the sender for this message.
   *
   * @return  The sender for this message.
   */
  public String getSender()
  {
    return sender;
  }
 
 
 
  /**
   * Specifies the sender for this message.
   *
   * @param  sender  The sender for this message.
   */
  public void setSender(String sender)
  {
    this.sender = sender;
  }
 
 
 
  /**
   * Retrieves the set of recipients for this message.  This list may be
   * directly manipulated by the caller.
   *
   * @return  The set of recipients for this message.
   */
  public List<String> getRecipients()
  {
    return recipients;
  }
 
 
 
  /**
   * Specifies the set of recipients for this message.
   *
   * @param  recipients The set of recipients for this message.
   */
  public void setRecipients(ArrayList<String> recipients)
  {
    this.recipients = recipients;
  }
 
 
 
  /**
   * Adds the specified recipient to this message.
   *
   * @param  recipient  The recipient to add to this message.
   */
  public void addRecipient(String recipient)
  {
    recipients.add(recipient);
  }
 
 
 
  /**
   * Retrieves the subject for this message.
   *
   * @return  The subject for this message.
   */
  public String getSubject()
  {
    return subject;
  }
 
 
 
  /**
   * Specifies the subject for this message.
   *
   * @param  subject  The subject for this message.
   */
  public void setSubject(String subject)
  {
    this.subject = subject;
  }
 
 
  /**
   * Retrieves the MIME Type for the body of this message.
   *
   * @return The MIME Type for this message.
   */
   public String getBodyMIMEType()
   {
     return bodyMIMEType;
   }
 
  /**
   * Specifies the MIME Type for the body of this message.
   *
   * @param bodyMIMEType  The MIME Type for this message.
   */
  public void setBodyMIMEType(String bodyMIMEType)
  {
    this.bodyMIMEType = bodyMIMEType;
  }
 
  /**
   * Retrieves the body for this message.  It may be directly manipulated by the
   * caller.
   *
   * @return  The body for this message.
   */
  public LocalizableMessageBuilder getBody()
  {
    return body;
  }
 
 
 
  /**
   * Specifies the body for this message.
   *
   * @param  body  The body for this message.
   */
  public void setBody(LocalizableMessageBuilder body)
  {
    this.body = body;
  }
 
 
 
  /**
   * Specifies the body for this message.
   *
   * @param  body  The body for this message.
   */
  public void setBody(LocalizableMessage body)
  {
    this.body = new LocalizableMessageBuilder(body);
  }
 
 
 
  /**
   * Appends the provided text to the body of this message.
   *
   * @param  text  The text to append to the body of the message.
   */
  public void appendToBody(String text)
  {
    body.append(text);
  }
 
 
 
  /**
   * Retrieves the set of attachments for this message.  This list may be
   * directly modified by the caller if desired.
   *
   * @return  The set of attachments for this message.
   */
  public List<MimeBodyPart> getAttachments()
  {
    return attachments;
  }
 
 
 
  /**
   * Adds the provided attachment to this mail message.
   *
   * @param  attachment  The attachment to add to this mail message.
   */
  public void addAttachment(MimeBodyPart attachment)
  {
    attachments.add(attachment);
  }
 
 
 
  /**
   * Adds an attachment to this mail message with the provided text.
   *
   * @param  attachmentText  The text to include in the attachment.
   *
   * @throws  MessagingException  If there is a problem of some type with the
   *                              attachment.
   */
  public void addAttachment(String attachmentText)
         throws MessagingException
  {
    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setText(attachmentText);
    attachments.add(attachment);
  }
 
 
 
  /**
   * Adds the provided attachment to this mail message.
   *
   * @param  attachmentFile  The file containing the attachment data.
   *
   * @throws  MessagingException  If there is a problem of some type with the
   *                              attachment.
   */
  private void addAttachment(File attachmentFile)
         throws MessagingException
  {
    MimeBodyPart attachment = new MimeBodyPart();
 
    FileDataSource dataSource = new FileDataSource(attachmentFile);
    attachment.setDataHandler(new DataHandler(dataSource));
    attachment.setFileName(attachmentFile.getName());
 
    attachments.add(attachment);
  }
 
 
 
  /**
   * Attempts to send this message to the intended recipient(s).  This will use
   * the mail server(s) defined in the Directory Server mail handler
   * configuration.  If multiple servers are specified and the first is
   * unavailable, then the other server(s) will be tried before returning a
   * failure to the caller.
   *
   * @throws  MessagingException  If a problem occurred while attempting to send
   *                              the message.
   */
  public void send()
         throws MessagingException
  {
    send(DirectoryServer.getCoreConfigManager().getMailServerPropertySets());
  }
 
 
 
  /**
   * Attempts to send this message to the intended recipient(s).  If multiple
   * servers are specified and the first is unavailable, then the other
   * server(s) will be tried before returning a failure to the caller.
   *
   * @param  mailServerPropertySets  A list of property sets providing
   *                                 information about the mail servers to use
   *                                 when sending the message.
   *
   * @throws  MessagingException  If a problem occurred while attempting to send
   *                              the message.
   */
  private void send(List<Properties> mailServerPropertySets)
         throws MessagingException
  {
    // Get information about the available mail servers that we can use.
    MessagingException sendException = null;
    for (Properties props : mailServerPropertySets)
    {
      // Get a session and use it to create a new message.
      Session session = Session.getInstance(props);
      MimeMessage message = new MimeMessage(session);
      message.setSubject(subject);
      message.setSentDate(new Date());
 
 
      // Add the sender address.  If this fails, then it's a fatal problem we'll
      // propagate to the caller.
      try
      {
        message.setFrom(new InternetAddress(sender));
      }
      catch (MessagingException me)
      {
        logger.traceException(me);
 
        LocalizableMessage msg = ERR_EMAILMSG_INVALID_SENDER_ADDRESS.get(sender, me.getMessage());
        throw new MessagingException(msg.toString(), me);
      }
 
 
      // Add the recipient addresses.  If any of them fail, then that's a fatal
      // problem we'll propagate to the caller.
      InternetAddress[] recipientAddresses =
           new InternetAddress[recipients.size()];
      for (int i=0; i < recipientAddresses.length; i++)
      {
        String recipient = recipients.get(i);
 
        try
        {
          recipientAddresses[i] = new InternetAddress(recipient);
        }
        catch (MessagingException me)
        {
          logger.traceException(me);
 
          LocalizableMessage msg = ERR_EMAILMSG_INVALID_RECIPIENT_ADDRESS.get(recipient, me.getMessage());
          throw new MessagingException(msg.toString(), me);
        }
      }
      message.setRecipients(
              javax.mail.Message.RecipientType.TO,
              recipientAddresses);
 
 
      // If we have any attachments, then the whole thing needs to be
      // multipart.  Otherwise, just set the text of the message.
      if (attachments.isEmpty())
      {
        message.setContent(body.toString(), bodyMIMEType);
      }
      else
      {
        MimeMultipart multiPart = new MimeMultipart();
 
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(body.toString());
        multiPart.addBodyPart(bodyPart);
 
        for (MimeBodyPart attachment : attachments)
        {
          multiPart.addBodyPart(attachment);
        }
 
        message.setContent(multiPart);
      }
 
 
      // Try to send the message.  If this fails, it can be a complete failure
      // or a partial one.  If it's a complete failure then try rolling over to
      // the next server.  If it's a partial one, then that likely means that
      // the message was sent but one or more recipients was rejected, so we'll
      // propagate that back to the caller.
      try
      {
        Transport.send(message);
        return;
      }
      catch (SendFailedException sfe)
      {
        logger.traceException(sfe);
 
        // We'll ignore this and hope that another server is available.  If not,
        // then at least save the exception so that we can throw it if all else
        // fails.
        if (sendException == null)
        {
          sendException = sfe;
        }
      }
      // FIXME -- Are there any other types of MessagingException that we might
      //          want to catch so we could try again on another server?
    }
 
 
    // If we've gotten here, then we've tried all of the servers in the list and
    // still failed.  If we captured an earlier exception, then throw it.
    // Otherwise, throw a generic exception.
    if (sendException != null)
    {
      throw sendException;
    }
    throw new MessagingException(ERR_EMAILMSG_CANNOT_SEND.get().toString());
  }
 
 
 
  /**
   * Provide a command-line mechanism for sending an e-mail message via SMTP.
   *
   * @param  args  The command-line arguments provided to this program.
   */
  public static void main(String[] args)
  {
    LocalizableMessage description = INFO_EMAIL_TOOL_DESCRIPTION.get();
    ArgumentParser argParser = new ArgumentParser(EMailMessage.class.getName(),
                                                  description, false);
 
    BooleanArgument showUsage  = null;
    StringArgument  attachFile = null;
    StringArgument  bodyFile   = null;
    StringArgument  host       = null;
    StringArgument  from       = null;
    StringArgument  subject    = null;
    StringArgument  to         = null;
 
    try
    {
      host =
              StringArgument.builder("host")
                      .shortIdentifier('h')
                      .description(INFO_EMAIL_HOST_DESCRIPTION.get())
                      .multiValued()
                      .required()
                      .defaultValue("127.0.0.1")
                      .valuePlaceholder(INFO_HOST_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      from =
              StringArgument.builder("from")
                      .shortIdentifier('f')
                      .description(INFO_EMAIL_FROM_DESCRIPTION.get())
                      .required()
                      .valuePlaceholder(INFO_ADDRESS_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      to =
              StringArgument.builder("to")
                      .shortIdentifier('t')
                      .description(INFO_EMAIL_TO_DESCRIPTION.get())
                      .multiValued()
                      .required()
                      .valuePlaceholder(INFO_ADDRESS_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      subject =
              StringArgument.builder("subject")
                      .shortIdentifier('s')
                      .description(INFO_EMAIL_SUBJECT_DESCRIPTION.get())
                      .required()
                      .valuePlaceholder(INFO_SUBJECT_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      bodyFile =
              StringArgument.builder("body")
                      .shortIdentifier('b')
                      .description(INFO_EMAIL_BODY_DESCRIPTION.get())
                      .multiValued()
                      .required()
                      .valuePlaceholder(INFO_PATH_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      attachFile =
              StringArgument.builder("attach")
                      .shortIdentifier('a')
                      .description(INFO_EMAIL_ATTACH_DESCRIPTION.get())
                      .multiValued()
                      .valuePlaceholder(INFO_PATH_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
 
      showUsage = showUsageArgument();
      argParser.addArgument(showUsage);
      argParser.setUsageArgument(showUsage);
    }
    catch (ArgumentException ae)
    {
      System.err.println(ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
      System.exit(1);
    }
 
    try
    {
      argParser.parseArguments(args);
    }
    catch (ArgumentException ae)
    {
      argParser.displayMessageAndUsageReference(System.err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
      System.exit(1);
    }
 
    if (showUsage.isPresent())
    {
      return;
    }
 
    LinkedList<Properties> mailServerProperties = new LinkedList<>();
    for (String s : host.getValues())
    {
      Properties p = new Properties();
      p.setProperty(SMTP_PROPERTY_HOST, s);
      mailServerProperties.add(p);
    }
 
    EMailMessage message = new EMailMessage(from.getValue(), to.getValues(),
                                            subject.getValue());
 
    for (String s : bodyFile.getValues())
    {
      try
      {
        File f = new File(s);
        if (! f.exists())
        {
          System.err.println(ERR_EMAIL_NO_SUCH_BODY_FILE.get(s));
          System.exit(1);
        }
 
        BufferedReader reader = new BufferedReader(new FileReader(f));
        while (true)
        {
          String line = reader.readLine();
          if (line == null)
          {
            break;
          }
 
          message.appendToBody(line);
          message.appendToBody("\r\n"); // SMTP says we should use CRLF.
        }
 
        reader.close();
      }
      catch (Exception e)
      {
        System.err.println(ERR_EMAIL_CANNOT_PROCESS_BODY_FILE.get(s,
                                getExceptionMessage(e)));
        System.exit(1);
      }
    }
 
    if (attachFile.isPresent())
    {
      for (String s : attachFile.getValues())
      {
        File f = new File(s);
        if (! f.exists())
        {
          System.err.println(ERR_EMAIL_NO_SUCH_ATTACHMENT_FILE.get(s));
          System.exit(1);
        }
 
        try
        {
          message.addAttachment(f);
        }
        catch (Exception e)
        {
          System.err.println(ERR_EMAIL_CANNOT_ATTACH_FILE.get(s,
                                  getExceptionMessage(e)));
        }
      }
    }
 
    try
    {
      message.send(mailServerProperties);
    }
    catch (Exception e)
    {
      System.err.println(ERR_EMAIL_CANNOT_SEND_MESSAGE.get(
                              getExceptionMessage(e)));
      System.exit(1);
    }
  }
}