Java Code Examples for javax.mail.internet.MimeMessage#addRecipients()

The following examples show how to use javax.mail.internet.MimeMessage#addRecipients() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MailHandler.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
private MimeMessage getMimeMessage(MailMessage m) throws Exception {
	log.debug("getMimeMessage");
	// Building MimeMessage
	MimeMessage msg = getBasicMimeMessage();
	msg.setSubject(m.getSubject(), UTF_8.name());
	String replyTo = m.getReplyTo();
	if (replyTo != null && isMailAddReplyTo()) {
		log.debug("setReplyTo {}", replyTo);
		if (MailUtil.isValid(replyTo)) {
			msg.setReplyTo(new InternetAddress[]{new InternetAddress(replyTo)});
		}
	}
	msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(m.getRecipients(), false));

	return m.getIcs() == null ? appendBody(msg, m) : appendIcsBody(msg, m);
}
 
Example 2
Source File: SmtpServerTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendAndWaitForIncomingMailsInBcc() throws Throwable {
    String subject = GreenMailUtil.random();
    String body = GreenMailUtil.random();
    final MimeMessage message = createTextEmail("test@localhost", "from@localhost", subject, body, greenMail.getSmtp().getServerSetup());
    message.addRecipients(Message.RecipientType.BCC, "bcc1@localhost,bcc2@localhost");

    assertEquals(0, greenMail.getReceivedMessages().length);

    GreenMailUtil.sendMimeMessage(message);

    assertTrue(greenMail.waitForIncomingEmail(1500, 3));

    MimeMessage[] emails = greenMail.getReceivedMessages();
    assertEquals(3, emails.length);
}
 
Example 3
Source File: GoogleMailResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
private Message createMessage(String body) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);

    Profile profile = producerTemplate.requestBody("google-mail://users/getProfile?inBody=userId", USER_ID, Profile.class);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(TO, profile.getEmailAddress());
    mm.setSubject(EMAIL_SUBJECT);
    mm.setContent(body, "text/plain");

    Message message = new Message();
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        mm.writeTo(baos);
        message.setRaw(Base64.getUrlEncoder().encodeToString(baos.toByteArray()));
    }
    return message;
}
 
Example 4
Source File: EmailNotifierBase.java    From DotCi with MIT License 6 votes vote down vote up
public MimeMessage createEmail(DynamicBuild build, BuildListener listener) throws AddressException, MessagingException {
    List<InternetAddress> to = getToEmailAddress(build, listener);

    String from = SetupConfig.get().getFromEmailAddress();
    Session session = Session.getDefaultInstance(System.getProperties());
    MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(from));

    message.addRecipients(Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()]));

    String subject = getNotificationMessage(build, listener);
    message.setSubject(subject);
    message.setText("Link to the build " + build.getAbsoluteUrl());
    return message;
}
 
Example 5
Source File: TestMailSending.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
private MimeMessage getMimeMessage() throws Exception {
	MailHandler h = new MailHandler();
	setSmtpServer(smtpServer);
	setSmtpPort(smtpPort);
	setSmtpUseTls(mailTls);
	setSmtpUser(mailAuthUser);
	setSmtpPass(mailAuthPass);
	setMailFrom(from);
	// Building MimeMessage
	MimeMessage msg = h.getBasicMimeMessage();
	msg.setSubject("getSubject()");
	msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]", false));

	return h.appendBody(msg, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
}
 
Example 6
Source File: MailUtil.java    From mail-micro-service with Apache License 2.0 5 votes vote down vote up
/**
 * 追加发件人
 * @author hf-hf
 * @date 2018/12/27 15:36
 */
private void addRecipients(MimeMessage message, Message.RecipientType type,
                           String recipients) throws MessagingException {
    String[] addresses = recipients.split(";");
    for (int i = 0; i < addresses.length; i++) {
        message.addRecipients(type, addresses[i]);
    }
}
 
Example 7
Source File: MailFeedbackSender.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Override
public void send(String subject, String body, String sender) {
    try {
        final String recipientList = StringUtils.join((new HashSet<>(Arrays.asList(recipients))).toArray(), ',');
        subject = subjectPrefix + subject;
        body = bodyPrefix + "<br/>" + body + "<br/>" + bodySuffix;

        InternetAddress from = new InternetAddress(this.sender);
        InternetAddress replyTo = new InternetAddress(sender);

        Properties p = new Properties();
        p.put("mail.smtp.host", smtpHost);
        p.put("mail.smtp.port", smtpPort);
        p.put("mail.smtp.starttls.enable", "true");
        p.put("mail.smtp.auth", "true");

        MailAuthenticator authenticator = new MailAuthenticator(userName, password);
        Session sendMailSession = Session.getInstance(p, authenticator);

        MimeMessage msg = new MimeMessage(sendMailSession);
        msg.setFrom(from);
        msg.setReplyTo(new Address[] { replyTo });
        msg.addRecipients(Message.RecipientType.TO, recipientList);

        msg.setSubject(subject, "UTF-8");
        msg.setSentDate(new Date());
        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(body, "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        msg.setContent(mainPart);
        Transport.send(msg);

        LOGGER.debug("Sending mail:'{}' to '{}'", subject, recipients);
    } catch (Exception e) {
        throw new TDPException(APIErrorCodes.UNABLE_TO_SEND_MAIL, e);
    }
}
 
Example 8
Source File: DefaultStaticDependenciesDelegator.java    From olat with Apache License 2.0 5 votes vote down vote up
@Override
public MimeMessage createMessage(InternetAddress from, List<? extends ContactList> listOfContactLists, String body, String subject, File[] attachments, MailerResult result)  throws AddressException, MessagingException {
	MimeMessage tmpMessage = MailHelper.createMessage();
	for (ContactList tmp : listOfContactLists) {
		InternetAddress groupName[] = InternetAddress.parse(tmp.getRFC2822Name() + ";");
		InternetAddress members[] = tmp.getEmailsAsAddresses();
		tmpMessage.addRecipients(RecipientType.TO, groupName);
		tmpMessage.addRecipients(RecipientType.BCC, members);
	}
	Address recipients[] = tmpMessage.getRecipients(RecipientType.TO);
	Address recipientsBCC[] = tmpMessage.getRecipients(RecipientType.BCC);
	
	return createMessage(from, recipients, null, recipientsBCC, body, subject, attachments, result);
}
 
Example 9
Source File: EmailMessageSender.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
protected boolean sendEmail(final String subject, final String content, final String userEmailAddress,
                            final String replyTo, final String personalFromName) {
    boolean success = true;
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(userEmailAddress));
            InternetAddress[] replyTos = new InternetAddress[1];
            if ((replyTo != null) && (!"".equals(replyTo))) {
                replyTos[0] = new InternetAddress(replyTo);
                mimeMessage.setReplyTo(replyTos);
            }
            InternetAddress fromAddress = new InternetAddress(getDefaultFromAddress());
            if (personalFromName != null)
                fromAddress.setPersonal(personalFromName);
            mimeMessage.setFrom(fromAddress);
            mimeMessage.setContent(content, "text/html; charset=utf-8");
            mimeMessage.setSubject(subject);
            logger.debug("sending email to [" + userEmailAddress + "]subject subject :[" + subject + "]");
        }
    };
    try {
        if (isAuthenticatedSMTP()) {
            emailService.send(preparator);
        } else {
            emailServiceNoAuth.send(preparator);
        }
    } catch (MailException ex) {
        // simply log it and go on...
        logger.error("Error sending email notification to:" + userEmailAddress, ex);

        success = false;
    }

    return success;
}
 
Example 10
Source File: TestSendIcalMessage.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
private void sendIcalMessage() throws Exception {
	log.debug("sendIcalMessage");

	// Building MimeMessage
	MimeMessage mimeMessage = mailHandler.getBasicMimeMessage();
	mimeMessage.setSubject(subject);
	mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));

	// -- Create a new message --
	BodyPart msg = new MimeBodyPart();
	msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody,
			"text/html; charset=\"utf-8\"")));

	Multipart multipart = new MimeMultipart();

	BodyPart iCalAttachment = new MimeBodyPart();
	iCalAttachment.setDataHandler(new DataHandler(
			new javax.mail.util.ByteArrayDataSource(
					new ByteArrayInputStream(iCalMimeBody),
					"text/calendar;method=REQUEST;charset=\"UTF-8\"")));
	iCalAttachment.setFileName("invite.ics");

	multipart.addBodyPart(iCalAttachment);
	multipart.addBodyPart(msg);

	mimeMessage.setSentDate(new Date());
	mimeMessage.setContent(multipart);

	// -- Set some other header information --
	// mimeMessage.setHeader("X-Mailer", "XML-Mail");
	// mimeMessage.setSentDate(new Date());

	// Transport trans = session.getTransport("smtp");
	Transport.send(mimeMessage);
}
 
Example 11
Source File: SendEmail.java    From Hybrid-Music-Recommender-System with MIT License 5 votes vote down vote up
private static MimeMessage createSimpleMail(Session session, String theme, String messages,String email) throws Exception {
	MimeMessage message = new MimeMessage(session);
	message.setFrom(new InternetAddress("[email protected]"));
	message.addRecipients(Message.RecipientType.TO, email);
	message.setSubject(theme);
	message.setText(messages);
	message.saveChanges();
	return message;
}
 
Example 12
Source File: MailUtil.java    From mail-micro-service with Apache License 2.0 5 votes vote down vote up
/**
 * 追加发件人
 * @author hf-hf
 * @date 2018/12/27 15:36
 */
private void addRecipients(MimeMessage message, Message.RecipientType type,
                           String recipients) throws MessagingException {
    String[] addresses = recipients.split(";");
    for (int i = 0; i < addresses.length; i++) {
        message.addRecipients(type, addresses[i]);
    }
}
 
Example 13
Source File: EmailSender.java    From kmanager with Apache License 2.0 4 votes vote down vote up
public static void sendEmail(String message, String sendTo, String group_topic) {
  Properties properties = System.getProperties();

  if (config.getSmtpAuth()) {
    properties.setProperty("mail.user", config.getSmtpUser());
    properties.setProperty("mail.password", config.getSmtpPasswd());
  }
  properties.setProperty("mail.smtp.host", config.getSmtpServer());

  Session session = Session.getDefaultInstance(properties);

  MimeMessage mimeMessage = new MimeMessage(session);

  try {
    String[] sendToArr = sendTo.split(";");
    mimeMessage.setFrom(new InternetAddress(config.getMailSender()));
    if (sendToArr.length > 1) {
      String cc = "";
      for (int i = 1; i < sendToArr.length; i++) {
        cc += i == sendToArr.length - 1 ? sendToArr[i] : sendToArr[i] + ",";
      }
      mimeMessage.addRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
    }
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(sendToArr[0]));

    String[] group_topicArr = group_topic.split("_");
    String subject = config.getMailSubject();
    if (subject.contains("{group}")) {
      subject = subject.replace("{group}", group_topicArr[0]);
    }
    if (subject.contains("{topic}")) {
      subject = subject.replace("{topic}", group_topicArr[1]);
    }
    mimeMessage.setSubject(subject);
    mimeMessage.setSentDate(new Date());
    mimeMessage.setContent(message, "text/html");

    Transport.send(mimeMessage);
  } catch (

  Exception e) {
    LOG.error("sendEmail faild!", e);
  }
}
 
Example 14
Source File: NeteaseMailUtil.java    From charging_pile_cloud with MIT License 4 votes vote down vote up
/**
 * 发送网页图片邮箱
 *
 * @param to
 * @param title
 * @param text
 * @return
 */
private static boolean sendMailHtml(String to, String title, String text) {
    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
    //SimpleMailMessage mailMessage = new SimpleMailMessage();

    //建立邮件消息,发送简单邮件和html邮件的区别
    MimeMessage mailMessage = senderImpl.createMimeMessage();

    Properties prop = new Properties();
    System.out.println("sendMail...util...");
    try {
        //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,
        //multipart模式
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

        prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        prop.setProperty("mail.smtp.socketFactory.fallback", "false");

        prop.setProperty("mail.smtp.port", "465");
        prop.setProperty("mail.smtp.socketFactory.port", "465");

        // 设置传输协议
        prop.setProperty("mail.transport.protocol", "smtp");

        prop.put("mail.smtp.auth", isAuth);
        prop.put("mail.smtp.timeout", linkTimeout);
        senderImpl.setJavaMailProperties(prop);
        senderImpl.setUsername(emailUsername);
        senderImpl.setPassword(authorizationPwd);
        //设定mail server
        senderImpl.setHost(emailHost);
        //senderImpl.setPort(587);

        // 设置收件人,寄件人 用数组发送多个邮件
        // String[] array = new String[]    {"[email protected]","[email protected]"};
        // mailMessage.setTo(array);
        messageHelper.setTo(to);
        messageHelper.setFrom(sendEmail);
        messageHelper.setSubject(title);
        messageHelper.setText(messageHtml(text), true);

        System.out.println("发送信息:" + text);

        MimeMessage msg = senderImpl.createMimeMessage();
        msg.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(sendEmail));
        //发送邮件
        senderImpl.send(mailMessage);

        System.out.println("发送邮件成功");

        return true;
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("发送邮件失败");
        return false;
    }
}
 
Example 15
Source File: GmailSendEmailCustomizer.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static com.google.api.services.gmail.model.Message createMessage(String to, String from, String subject,
        String bodyText, String cc, String bcc) throws MessagingException, IOException {

    if (ObjectHelper.isEmpty(to)) {
        throw new RuntimeCamelException("Cannot create gmail message as no 'to' address is available");
    }

    if (ObjectHelper.isEmpty(from)) {
        throw new RuntimeCamelException("Cannot create gmail message as no 'from' address is available");
    }

    if (ObjectHelper.isEmpty(subject)) {
        LOG.warn("New gmail message wil have no 'subject'. This may not be want you wanted?");
    }

    if (ObjectHelper.isEmpty(bodyText)) {
        LOG.warn("New gmail message wil have no 'body text'. This may not be want you wanted?");
    }

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    email.addRecipients(javax.mail.Message.RecipientType.TO, getAddressesList(to));
    email.setSubject(subject);
    email.setText(bodyText);
    if (ObjectHelper.isNotEmpty(cc)) {
        email.addRecipients(javax.mail.Message.RecipientType.CC, getAddressesList(cc));
    }
    if (ObjectHelper.isNotEmpty(bcc)) {
        email.addRecipients(javax.mail.Message.RecipientType.BCC, getAddressesList(bcc));
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    email.writeTo(buffer);
    byte[] bytes = buffer.toByteArray();
    String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
    com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message();
    message.setRaw(encodedEmail);
    return message;
}
 
Example 16
Source File: MailSender.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
public void sendMail(EmailBean emailBean) throws SendMailException {
  File tempDir = null;
  try {
    MimeMessage message = new MimeMessage(mailSessionProvider.get());
    Multipart contentPart = new MimeMultipart();

    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType()));
    contentPart.addBodyPart(bodyPart);

    if (emailBean.getAttachments() != null) {
      tempDir = Files.createTempDir();
      for (Attachment attachment : emailBean.getAttachments()) {
        // Create attachment file in temporary directory
        byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent());
        File attachmentFile = new File(tempDir, attachment.getFileName());
        Files.write(attachmentContent, attachmentFile);

        // Attach the attachment file to email
        MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.attachFile(attachmentFile);
        attachmentPart.setContentID("<" + attachment.getContentId() + ">");
        contentPart.addBodyPart(attachmentPart);
      }
    }

    message.setContent(contentPart);
    message.setSubject(emailBean.getSubject(), "UTF-8");
    message.setFrom(new InternetAddress(emailBean.getFrom(), true));
    message.setSentDate(new Date());
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo()));

    if (emailBean.getReplyTo() != null) {
      message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo()));
    }
    LOG.info(
        "Sending from {} to {} with subject {}",
        emailBean.getFrom(),
        emailBean.getTo(),
        emailBean.getSubject());

    Transport.send(message);
    LOG.debug("Mail sent");
  } catch (Exception e) {
    LOG.error(e.getLocalizedMessage());
    throw new SendMailException(e.getLocalizedMessage(), e);
  } finally {
    if (tempDir != null) {
      try {
        FileUtils.deleteDirectory(tempDir);
      } catch (IOException exception) {
        LOG.error(exception.getMessage());
      }
    }
  }
}
 
Example 17
Source File: MailOutput.java    From NNAnalytics with Apache License 2.0 4 votes vote down vote up
/**
 * Write and send an email.
 *
 * @param subject email subject
 * @param html the exact html to send out via email
 * @param mailHost email host
 * @param emailTo email to address
 * @param emailCc email cc addresses
 * @param emailFrom email from address
 * @throws Exception if email fails to send
 */
public static void write(
    String subject,
    String html,
    String mailHost,
    String[] emailTo,
    String[] emailCc,
    String emailFrom)
    throws Exception {

  InternetAddress[] to = new InternetAddress[emailTo.length];
  for (int i = 0; i < emailTo.length && i < to.length; i++) {
    to[i] = new InternetAddress(emailTo[i]);
  }

  InternetAddress[] cc = null;
  if (emailCc != null) {
    cc = new InternetAddress[emailCc.length];
    for (int i = 0; i < emailCc.length && i < cc.length; i++) {
      cc[i] = new InternetAddress(emailCc[i]);
    }
  }

  // Sender's email ID needs to be mentioned
  InternetAddress from = new InternetAddress(emailFrom);

  // Get system properties
  Properties properties = System.getProperties();

  // Setup mail server
  properties.setProperty(MAIL_SMTP_HOST, mailHost);

  // Get the Session object.
  Session session = Session.getInstance(properties);

  // Create a default MimeMessage object.
  MimeMessage message = new MimeMessage(session);

  // INodeSet From: header field of the header.
  message.setFrom(from);

  // INodeSet To: header field of the header.
  message.addRecipients(Message.RecipientType.TO, to);
  if (cc != null && cc.length != 0) {
    message.addRecipients(Message.RecipientType.CC, cc);
  }

  // INodeSet Subject: header field
  message.setSubject(subject);

  // Send the actual HTML message, as big as you like
  MimeBodyPart bodyHtml = new MimeBodyPart();
  bodyHtml.setContent(html, MAIL_CONTENT_TEXT_HTML);

  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(bodyHtml);

  message.setContent(multipart);

  // Send message
  Transport.send(message);
}
 
Example 18
Source File: EmailAlerter.java    From karaf-decanter with Apache License 2.0 4 votes vote down vote up
@Override
public void handleEvent(Event event) {
    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        // set from
        if (event.getProperty("from") != null) {
            message.setFrom(new InternetAddress(event.getProperty("from").toString()));
        } else if (event.getProperty("alert.email.from") != null) {
            message.setFrom(new InternetAddress(event.getProperty("alert.email.from").toString()));
        } else if (from != null){
            message.setFrom(from);
        } else {
            message.setFrom("[email protected]");
        }
        // set to
        if (event.getProperty("to") != null) {
            message.addRecipients(Message.RecipientType.TO, event.getProperty("to").toString());
        } else if (event.getProperty("alert.email.to") != null) {
            message.addRecipients(Message.RecipientType.TO, event.getProperty("alert.email.to").toString());
        } else if (to != null) {
            message.addRecipients(Message.RecipientType.TO, to);
        } else {
            LOGGER.warn("to destination is not defined");
            return;
        }
        // set cc
        if (event.getProperty("cc") != null) {
            message.addRecipients(Message.RecipientType.CC, event.getProperty("cc").toString());
        } else if (event.getProperty("alert.email.cc") != null) {
            message.addRecipients(Message.RecipientType.CC, event.getProperty("alert.email.cc").toString());
        } else if (cc != null) {
            message.addRecipients(Message.RecipientType.CC, cc);
        }
        // set bcc
        if (event.getProperty("bcc") != null) {
            message.addRecipients(Message.RecipientType.BCC, event.getProperty("bcc").toString());
        } else if (event.getProperty("alert.email.bcc") != null) {
            message.addRecipients(Message.RecipientType.BCC, event.getProperty("alert.email.bcc").toString());
        } else if (bcc != null) {
            message.addRecipients(Message.RecipientType.BCC, bcc);
        }
        // set subject
        message.setSubject(formatter.formatSubject(subjectTemplate, event));
        // set body
        String contentType = bodyType;
        contentType = (event.getProperty("body.type") != null) ? event.getProperty("body.type").toString() : contentType;
        contentType = (event.getProperty("alert.email.body.type") != null) ? event.getProperty("alert.email.body.type").toString() : contentType;
        message.setContent(formatter.formatBody(bodyTemplate, event), contentType);
        // send email
        if (properties.get("mail.smtp.user") != null) {
            Transport.send(message, (String) properties.get("mail.smtp.user"), (String) properties.get("mail.smtp.password"));
        } else {
            Transport.send(message);
        }
    } catch (Exception e) {
        LOGGER.error("Can't send the alert e-mail", e);
    }
}
 
Example 19
Source File: MailerImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * Send an email to the given recipients with the specified subject and message.
 * 
 * @param from
 *            sender of the message            
 * @param to
 *            list of addresses to which the message is sent
 * @param subject
 *            subject of the message
 * @param messageBody
 *            body of the message
 * @param cc
 *            list of addresses which are to be cc'd on the message
 * @param bcc
 *            list of addresses which are to be bcc'd on the message
 */
protected void sendMessage(String from, Address[] to, String subject, String messageBody, Address[] cc, Address[] bcc, boolean htmlMessage) throws AddressException, MessagingException, MailException {
 MimeMessage message = mailSender.createMimeMessage();

    // From Address
    message.setFrom(new InternetAddress(from));

    // To Address(es)
    if (to != null && to.length > 0) {
        message.addRecipients(Message.RecipientType.TO, to);
    } else {
        LOG.error("No recipients indicated.");
    }

    // CC Address(es)
    if (cc != null && cc.length > 0) {
        message.addRecipients(Message.RecipientType.CC, cc);
    }

    // BCC Address(es)
    if (bcc != null && bcc.length > 0) {
        message.addRecipients(Message.RecipientType.BCC, bcc);
    }

    // Subject
    message.setSubject(subject);
    if (subject == null || "".equals(subject)) {
        LOG.warn("Empty subject being sent.");
    }

    // Message body.
    if (htmlMessage) {
        prepareHtmlMessage(messageBody, message);
    } else {
        message.setText(messageBody);
        if (messageBody == null || "".equals(messageBody)) {
            LOG.warn("Empty message body being sent.");
        }
    }

    // Send the message
    try {
    	mailSender.send(message);
    }
    catch (Exception e) {
    	LOG.error("sendMessage(): ", e);
    	throw new RuntimeException(e);
    }
}
 
Example 20
Source File: SingularitySmtpSender.java    From Singularity with Apache License 2.0 4 votes vote down vote up
private void sendMail(
  List<String> toList,
  List<String> ccList,
  String subject,
  String body
) {
  final SMTPConfiguration smtpConfiguration = maybeSmtpConfiguration.get();

  boolean useAuth = false;

  if (
    smtpConfiguration.getUsername().isPresent() &&
    smtpConfiguration.getPassword().isPresent()
  ) {
    useAuth = true;
  } else if (
    smtpConfiguration.getUsername().isPresent() ||
    smtpConfiguration.getPassword().isPresent()
  ) {
    LOG.warn(
      "Not using smtp authentication because username ({}) or password ({}) was not present",
      smtpConfiguration.getUsername().isPresent(),
      smtpConfiguration.getPassword().isPresent()
    );
  }

  try {
    final Session session = createSession(smtpConfiguration, useAuth);

    MimeMessage message = new MimeMessage(session);

    Address[] toArray = getAddresses(toList);
    message.addRecipients(RecipientType.TO, toArray);

    if (!ccList.isEmpty()) {
      Address[] ccArray = getAddresses(ccList);
      message.addRecipients(RecipientType.CC, ccArray);
    }

    message.setFrom(new InternetAddress(smtpConfiguration.getFrom()));

    message.setSubject(MimeUtility.encodeText(subject, "utf-8", null));
    message.setContent(body, "text/html; charset=utf-8");

    LOG.trace(
      "Sending a message to {} - {}",
      Arrays.toString(toArray),
      getEmailLogFormat(toList, subject)
    );

    Transport.send(message);
  } catch (Throwable t) {
    LOG.warn("Unable to send message {}", getEmailLogFormat(toList, subject), t);
    exceptionNotifier.notify(
      String.format("Unable to send message (%s)", t.getMessage()),
      t,
      ImmutableMap.of("subject", subject)
    );
  }
}