Example usage for javax.mail.internet MimeMessage addRecipients

List of usage examples for javax.mail.internet MimeMessage addRecipients

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage addRecipients.

Prototype

public void addRecipients(Message.RecipientType type, String addresses) throws MessagingException 

Source Link

Document

Add the given addresses to the specified recipient type.

Usage

From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java

private void sendIcalMessage() throws Exception {

    log.debug("sendIcalMessage");

    // Evaluating Configuration Data
    String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value();
    String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value();
    // String from = "openmeetings@xmlcrm.org";
    String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value();

    String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value();
    String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.port", smtpPort);

    Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable");
    if (conf != null) {
        if (conf.getConf_value().equals("1")) {
            props.put("mail.smtp.starttls.enable", "true");
        }//from  ww w . ja v a 2  s  .c om
    }

    // Check for Authentification
    Session session = null;
    if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null
            && emailUserpass.length() > 0) {
        // use SMTP Authentication
        props.put("mail.smtp.auth", "true");
        session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass));
    } else {
        // not use SMTP Authentication
        session = Session.getDefaultInstance(props, null);
    }

    // Building MimeMessage
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setFrom(new InternetAddress(from));
    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);

}

From source file:com.threewks.thundr.gmail.GmailMailer.java

private MimeMessage createMime(String bodyText, String subject, Map<String, String> to, List<Attachment> pdfs)
        throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage email = new MimeMessage(session);
    Set<InternetAddress> toAddresses = getInternetAddresses(to);

    if (!toAddresses.isEmpty()) {
        email.addRecipients(javax.mail.Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[to.size()]));
    }/*from  w ww . j  a  va  2 s .  c o  m*/

    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/html");
    mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    for (Attachment attachmentPdf : pdfs) {
        MimeBodyPart attachment = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(attachmentPdf.getData(), "application/pdf");
        attachment.setDataHandler(new DataHandler(source));
        attachment.setFileName(attachmentPdf.getFileName());
        multipart.addBodyPart(mimeBodyPart);
        multipart.addBodyPart(attachment);
    }
    email.setContent(multipart);
    return email;
}

From source file:com.threewks.thundr.gmail.GmailMailer.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to       Email address of the receiver.
 * @param from     Email address of the sender, the mailbox account.
 * @param subject  Subject of the email.
 * @param bodyText Body text of the email.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException/*w w w  .  jav a 2s . co  m*/
 */
protected MimeMessage createEmailWithAttachment(Set<InternetAddress> to, InternetAddress from,
        Set<InternetAddress> cc, Set<InternetAddress> bcc, InternetAddress replyTo, String subject,
        String bodyText, List<com.threewks.thundr.mail.Attachment> attachments) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    try {

        email.setFrom(from);

        if (to != null) {
            email.addRecipients(javax.mail.Message.RecipientType.TO,
                    to.toArray(new InternetAddress[to.size()]));
        }
        if (cc != null) {
            email.addRecipients(javax.mail.Message.RecipientType.CC,
                    cc.toArray(new InternetAddress[cc.size()]));
        }
        if (bcc != null) {
            email.addRecipients(javax.mail.Message.RecipientType.BCC,
                    bcc.toArray(new InternetAddress[bcc.size()]));
        }
        if (replyTo != null) {
            email.setReplyTo(new Address[] { replyTo });
        }

        email.setSubject(subject);

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(bodyText, "text/html");
        mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

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

        if (attachments != null) {
            for (com.threewks.thundr.mail.Attachment attachment : attachments) {
                mimeBodyPart = new MimeBodyPart();

                BasicViewRenderer renderer = new BasicViewRenderer(viewResolverRegistry);
                renderer.render(attachment.view());
                byte[] data = renderer.getOutputAsBytes();
                String attachmentContentType = renderer.getContentType();
                String attachmentCharacterEncoding = renderer.getCharacterEncoding();

                populateMimeBodyPart(mimeBodyPart, attachment, data, attachmentContentType,
                        attachmentCharacterEncoding);

                multipart.addBodyPart(mimeBodyPart);
            }
        }

        email.setContent(multipart);
    } catch (MessagingException e) {
        Logger.error(e.getMessage());
        Logger.error(
                "Failed to create email from: %s;%s, to: %s, cc: %s, bcc: %s, replyTo %s;%s, subject %s, body %s, number of attachments %d",
                from.getAddress(), from.getPersonal(), Transformers.InternetAddressesToString.from(to),
                Transformers.InternetAddressesToString.from(cc),
                Transformers.InternetAddressesToString.from(bcc),
                replyTo == null ? "null" : replyTo.getAddress(),
                replyTo == null ? "null" : replyTo.getPersonal(), subject, bodyText,
                attachments == null ? 0 : attachments.size());
        throw new GmailException(e);
    }

    return email;
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testSaveNewMessage() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTest", ".eml");

    outputFile.deleteOnExit();/*from  w w  w . ja v a 2  s .c  om*/

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessage(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testSaveNewMessageRaw() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTestRaw", ".eml");

    outputFile.deleteOnExit();//from w  w  w.j  a  v a 2  s . com

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessageRaw(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}

From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java

/**
 * To set receiptent's mail ids in message to be sent.
 * //from  www. j av  a 2s . c  om
 * @param receiptentType {@link RecipientType}
 * @param mimeMessage {@link MimeMessage}
 * @param addressList {@link List}
 */
private void setAddressToMessage(RecipientType receiptentType, MimeMessage mimeMessage,
        List<String> addressList) {
    try {
        for (String address : addressList) {
            mimeMessage.addRecipients(receiptentType, address);
        }
    } catch (MessagingException messagingException) {
        throw new SendMailException(new StringBuilder()
                .append("Error while setting address. PLease verify email addresses").toString(),
                messagingException);
    }

}

From source file:org.b3log.solo.mail.local.MailSender.java

/**
 * Converts the specified message into a {@link javax.mail.Message
 * javax.mail.Message}./*from ww w .  j  a  va 2 s  . co  m*/
 *
 * @param message the specified message
 * @return a {@link javax.mail.internet.MimeMessage}
 * @throws Exception if converts error
 */
public javax.mail.Message convert2JavaMailMsg(final Message message) throws Exception {
    if (null == message) {
        return null;
    }

    if (StringUtils.isBlank(message.getFrom())) {
        throw new MessagingException("Null from");
    }

    if (null == message.getRecipients() || message.getRecipients().isEmpty()) {
        throw new MessagingException("Null recipients");
    }

    final MimeMessage ret = new MimeMessage(getSession());

    ret.setFrom(new InternetAddress(message.getFrom()));
    final String subject = message.getSubject();

    ret.setSubject(MimeUtility.encodeText(subject != null ? subject : "", "UTF-8", "B"));
    final String htmlBody = message.getHtmlBody();

    ret.setContent(htmlBody != null ? htmlBody : "", "text/html;charset=UTF-8");
    ret.addRecipients(RecipientType.TO, transformRecipients(message.getRecipients()));

    return ret;
}

From source file:net.sf.jclal.util.mail.SenderEmail.java

/**
 * Send the email with the indicated parameters
 *
 * @param subject The subject/*ww w.jav  a2  s. co m*/
 * @param content The content
 * @param reportFile The reportFile to send
 */
public void sendEmail(String subject, String content, File reportFile) {

    // Get system properties
    Properties properties = new Properties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);

    if (!user.isEmpty() && !pass.isEmpty()) {

        properties.setProperty("mail.user", user);

        properties.setProperty("mail.password", pass);
    }

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

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

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, toRecipients.toString());

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

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(content);

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        if (attachReporFile) {

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile)));
            messageBodyPart.setFileName(reportFile.getName());
            multipart.addBodyPart(messageBodyPart);
        }

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {

        Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e);
    }

}

From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java

private void sendMessage(String subject, String message, InternetAddress from, InternetAddress[] recipients,
        InternetAddress[] cclist, File attachedFile) throws MessagingException, IOException {
    log.info("try to send: " + printEmail(subject, message, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
    log.info("host: " + host + ", useSMTPS: " + useSmtps);
    Properties props = new Properties();
    String protocol = "smtp";
    if (useSmtps) // need smtps to test with gmail
    {//from ww w  . j av a2  s.  c o m
        props.put("mail.smtps.auth", "true");
        protocol = "smtps";
    }
    Session session = Session.getDefaultInstance(props, null);
    Transport t = session.getTransport(protocol);

    try {
        MimeMessage msg = new MimeMessage(session);
        if (this.replyTos != null)
            msg.setReplyTo(replyTos);
        msg.setFrom(from);
        msg.setSubject(subject);

        if (attachedFile != null) {
            setFileAsAttachment(msg, message, attachedFile);
        } else {
            msg.setContent(message, "text/plain");
        }

        msg.addRecipients(Message.RecipientType.TO, recipients);
        if (cclist != null)
            msg.addRecipients(Message.RecipientType.CC, cclist);

        t.connect(host, username, password);
        t.sendMessage(msg, msg.getAllRecipients());
    } finally {
        t.close();
    }
    log.info("sent: " + printEmailHeader(subject, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
}

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

protected void addRecipients(MimeMessage message, RecipientType recipientType, Collection<String> addresses)
        throws MessagingException {
    if (addresses != null && !addresses.isEmpty()) {
        Address[] addressArray = new Address[addresses.size()];
        int index = 0;
        for (String address : addresses) {
            addressArray[index++] = new InternetAddress(address);
        }/* w w  w . j a  va2s  .  c  o  m*/
        message.addRecipients(recipientType, addressArray);
    }
}