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.latticesoft.util.resource.MessageUtil.java

/**
 * Sends the email./*from   w  w  w. ja  va  2 s  .  co  m*/
 * @param info the EmailInfo containing the message and other details
 * @param p the properties to set in the environment when instantiating the session
 * @param auth the authenticator
 */
public static void sendMail(EmailInfo info, Properties p, Authenticator auth) {
    try {
        if (p == null) {
            if (log.isErrorEnabled()) {
                log.error("Null properties!");
            }
            return;
        }
        Session session = Session.getInstance(p, auth);
        session.setDebug(true);
        if (log.isInfoEnabled()) {
            log.info(p);
            log.info(session);
        }
        MimeMessage mimeMessage = new MimeMessage(session);
        if (log.isInfoEnabled()) {
            log.info(mimeMessage);
            log.info(info.getFromAddress());
        }
        mimeMessage.setFrom(info.getFromAddress());
        mimeMessage.setSentDate(new Date());
        List l = info.getToList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                if (log.isInfoEnabled()) {
                    log.info(addr);
                }
                mimeMessage.addRecipients(Message.RecipientType.TO, addr);
            }
        }
        l = info.getCcList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.CC, addr);
            }
        }
        l = info.getBccList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.BCC, addr);
            }
        }

        if (info.getAttachment().size() == 0) {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
                mimeMessage.setText(info.getContent(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
                mimeMessage.setText(info.getContent());
            }
            mimeMessage.setContent(info.getContent(), info.getContentType());
        } else {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
            }
            Multipart mp = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();
            if (info.getCharSet() != null) {
                body.setText(info.getContent(), info.getCharSet());
                body.setContent(info.getContent(), info.getContentType());
            } else {
                body.setText(info.getContent());
                body.setContent(info.getContent(), info.getContentType());
            }
            mp.addBodyPart(body);
            for (int i = 0; i < info.getAttachment().size(); i++) {
                String filename = (String) info.getAttachment().get(i);
                MimeBodyPart attachment = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(filename);
                attachment.setDataHandler(new DataHandler(fds));
                attachment.setFileName(MimeUtility.encodeWord(fds.getName()));
                mp.addBodyPart(attachment);
            }
            mimeMessage.setContent(mp);
        }
        Transport.send(mimeMessage);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error in sending email", e);
        }
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Sends a mail message. The content must be provided as MimeBodyPart objects.
 *
 * @param from      Sender's email address.
 * @param to        Recipient's email address.
 * @param cc        Email address for CC.
 * @param bcc       Email address for BCC.
 * @param subject   Subject text for the email.
 * @param bodyParts The body parts to insert into the message.
 * @throws SystemException        if an unexpected error occurs.
 * @throws ConfigurationException if a configuration error occurs.
 */// ww w.  j av a  2  s.c o  m
public static void send(String from, String to, String cc, String bcc, String subject, MimeBodyPart[] bodyParts)
        throws ConfigurationException, SystemException {

    initEventLog();

    try {
        Properties props = new Properties();

        Configuration config = Aksess.getConfiguration();
        String host = config.getString("mail.host");
        if (host == null) {
            throw new ConfigurationException("mail.host");
        }

        // I noen tilfeller nsker vi at all epost skal g til en testadresse
        String catchAllTo = config.getString("mail.catchall.to");
        boolean catchallExists = catchAllTo != null && catchAllTo.contains("@");
        if (catchallExists) {
            StringBuilder prefix = new StringBuilder(" (original recipient: " + to);
            if (cc != null) {
                prefix.append(", cc: ").append(cc);
            }
            if (bcc != null) {
                prefix.append(", bcc: ").append(bcc);
            }
            prefix.append(") ");
            subject = prefix + subject;
            to = catchAllTo;
            cc = null;
            bcc = null;
        }

        props.setProperty("mail.smtp.host", host);

        Session session = Session.getDefaultInstance(props);

        boolean debug = config.getBoolean("mail.debug", false);
        if (debug) {
            session.setDebug(true);
        }

        // Opprett message, sett attributter
        MimeMessage message = new MimeMessage(session);
        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress[] = InternetAddress.parse(to);

        message.setFrom(fromAddress);

        if (toAddress.length > 1) {
            message.setRecipients(Message.RecipientType.BCC, toAddress);
        } else {
            message.setRecipients(Message.RecipientType.TO, toAddress);
        }
        if (cc != null) {
            message.addRecipients(Message.RecipientType.CC, cc);
        }
        if (bcc != null) {
            message.addRecipients(Message.RecipientType.BCC, bcc);
        }

        message.setSubject(subject, "ISO-8859-1");
        message.setSentDate(new Date());

        Multipart mp = new MimeMultipart();
        for (MimeBodyPart bodyPart : bodyParts) {
            mp.addBodyPart(bodyPart);
        }
        message.setContent(mp);

        // Send meldingen
        Transport.send(message);

        eventLog.log("System", null, Event.EMAIL_SENT, to + ":" + subject, null);

        // Logg sending
        log.info("Sending email to " + to + " with subject " + subject);
    } catch (MessagingException e) {
        String errormessage = "Subject: " + subject + " | Error: " + e.getMessage();
        eventLog.log("System", null, Event.FAILED_EMAIL_SUBMISSION, errormessage + " | to: " + to, null);
        log.error("Error sending mail", e);
        throw new SystemException("Error sending email to : " + to + " with subject " + subject, e);
    }
}

From source file:org.apache.camel.component.mail.MailBinding.java

private static void appendRecipientToMimeMessage(MimeMessage mimeMessage, String type, String recipient)
        throws MessagingException {

    // we support that multi recipient can be given as a string separated by comma or semicolon
    // regex ignores comma and semicolon inside of double quotes
    String[] lines = recipient.split("[,;]++(?=(?:(?:[^\\\"]*+\\\"){2})*+[^\\\"]*+$)");
    for (String line : lines) {
        line = line.trim();/*w w w .  j  a v a2s .  co  m*/
        mimeMessage.addRecipients(asRecipientType(type), line);
    }
}

From source file:org.apache.camel.component.google.mail.GmailUsersThreadsIntegrationTest.java

private Message createThreadedTestEmail(String previousThreadId) throws MessagingException, IOException {
    com.google.api.services.gmail.model.Profile profile = requestBody(
            "google-mail://users/getProfile?inBody=userId", CURRENT_USERID);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(javax.mail.Message.RecipientType.TO, profile.getEmailAddress());
    mm.setSubject("Hello from camel-google-mail");
    mm.setContent("Camel rocks!", "text/plain");
    Message createMessageWithEmail = createMessageWithEmail(mm);
    if (previousThreadId != null) {
        createMessageWithEmail.setThreadId(previousThreadId);
    }//from   w  w  w .j a v  a2s.  c  om

    Map<String, Object> headers = new HashMap<String, Object>();
    // parameter type is String
    headers.put("CamelGoogleMail.userId", CURRENT_USERID);
    // parameter type is com.google.api.services.gmail.model.Message
    headers.put("CamelGoogleMail.content", createMessageWithEmail);

    return requestBodyAndHeaders("google-mail://messages/send", null, headers);
}

From source file:org.trustedanalytics.user.invite.EmailService.java

@Override
public void sendMimeMessage(String email, String subject, String htmlContent) {
    MimeMessage message = mailSender.createMimeMessage();
    try {//from w  ww . ja v  a2s. c  om
        message.addFrom(senderAddresses);
        message.addRecipients(Message.RecipientType.TO, email);
        message.setSubject(subject);
        message.setContent(htmlContent, "text/html");
    } catch (Exception e) {
        LOGGER.error(e);
    }
    mailSender.send(message);
}

From source file:nz.co.testamation.common.mail.MimeMessageFactoryImpl.java

private void addRecipients(MimeMessage mimeMessage, Message.RecipientType type, String emailAddresses)
        throws MessagingException {
    if (StringUtils.isNotBlank(emailAddresses)) {
        mimeMessage.addRecipients(type, emailAddresses);
    }//ww  w .  j a v  a 2  s  .  c o  m
}

From source file:org.apache.axis2.transport.mail.MailClient.java

public void sendMessage(String to, String subject, String content, String soapAction)
        throws MessagingException {
    log.info("SENDING message from " + from + " to " + to);

    MimeMessage msg = new MimeMessage(session);

    msg.setHeader("transport.mail.soapaction", soapAction);
    msg.addRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject);/*from w w w .  j a  v  a2s  .c  om*/
    msg.setText(content);
    Transport.send(msg);
}

From source file:org.apache.camel.component.google.mail.GmailUsersMessagesIntegrationTest.java

private Message createTestEmail() throws MessagingException, IOException {
    com.google.api.services.gmail.model.Profile profile = requestBody(
            "google-mail://users/getProfile?inBody=userId", CURRENT_USERID);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(javax.mail.Message.RecipientType.TO, profile.getEmailAddress());
    mm.setSubject("Hello from camel-google-mail");
    mm.setContent("Camel rocks!", "text/plain");
    Message createMessageWithEmail = createMessageWithEmail(mm);
    return createMessageWithEmail;
}

From source file:org.obm.imap.archive.services.MailerImpl.java

@Override
public void send(ObmDomain domain, ArchiveTreatmentRunId runId, State state, Mailing mailing)
        throws MessagingException, URISyntaxException {
    try {//  w  ww  .  java2 s .  co  m
        if (!mailing.getEmailAddresses().isEmpty()) {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(from(domain));
            message.addRecipients(RecipientType.TO, internetAddresses(mailing));
            message.setSubject("End of IMAP Archive for domain " + domain.getName());
            message.setText(text(domain, runId, state), Charsets.UTF_8.name());

            smtpService.sendEmail(message, session);
        }
    } catch (MessagingException | URISyntaxException e) {
        logger.error("Error when mailing", e);
        throw e;
    }
}

From source file:org.xsocket.connection.SimpleSmtpClient.java

public void send(String contentType, String text, String from, String to)
        throws IOException, MessagingException {
    MimeMessage msg = new MimeMessage((Session) null);
    msg.setContent(text, contentType);//  ww w. ja v  a 2 s. c  om
    msg.addFrom(InternetAddress.parse(from));
    msg.addRecipients(RecipientType.TO, InternetAddress.parse(to));

    send(msg);
}