Example usage for javax.mail.internet MimeMessage addRecipient

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

Introduction

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

Prototype

public void addRecipient(RecipientType type, Address address) throws MessagingException 

Source Link

Document

Add this recipient address to the existing ones of the given type.

Usage

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {/*from   w ww  .j  a  v  a  2 s  . c  o  m*/
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:org.beanfuse.notification.mail.AbstractMailNotifier.java

private void addRecipient(MimeMessage message, RecipientType recipientType, String[] recipients)
        throws AddressException, MessagingException {
    if (null != recipients) {
        for (int i = 0; i < recipients.length; i++) {
            InternetAddress to = new InternetAddress(recipients[i].trim());
            message.addRecipient(recipientType, to);
        }/* w  w w  .  ja va2 s  . co m*/
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.ExceptionHandlingAction.java

private void sendEmail(String from, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host",
            Objects.firstNonNull(FenixConfigurationManager.getConfiguration().getMailSmtpHost(), "localhost"));
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    try {//from   w  ww .jav  a 2 s. com
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress()));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (Exception e) {
        logger.error("Could not send support email! Original message was: " + body, e);
    }
}

From source file:com.linuxbox.enkive.statistics.StatsReportEmailer.java

public void sendReport() {

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

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

    // 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.
        for (String toAddress : to.split(";")) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
        }/*  w  w w  .  j  a  v  a 2s.co m*/

        // Set Subject: header field
        message.setSubject("Enkive Status Report");

        // Now set the actual message
        message.setText(buildReport());

        // Send message
        Transport.send(message);
    } catch (MessagingException mex) {
        LOGGER.warn("Error sending statistics report email", mex);
    }
}

From source file:org.tsm.concharto.lab.LabJavaMail.java

private void sendConfirmationEmail(User user) {
    //mailSender.setHost("skipper");
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(user.getEmail());//ww  w  .  j  a  v  a  2s  .  c o  m
    String messageText = StringUtils.replace(WELCOME_MESSAGE, PARAM_NAME, user.getUsername());
    message.setText(messageText);
    message.setSubject(WELCOME_SUBJECT);
    message.setFrom("<Concharto Notifications> notify@concharto.com");

    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    InternetAddress from = new InternetAddress();
    from.setAddress("notify@concharto.com");
    InternetAddress to = new InternetAddress();
    to.setAddress(user.getEmail());
    try {
        from.setPersonal("Concharto Notifications");
        mimeMessage.addRecipient(Message.RecipientType.TO, to);
        mimeMessage.setSubject(WELCOME_SUBJECT);
        mimeMessage.setText(messageText);
        mimeMessage.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mailSender.setHost("localhost");
    mailSender.send(mimeMessage);

    /*
    Confirm your registration with Concharto
            
    Hello sanmi,
            
    Welcome to the Concharto community!
            
    Please click on this link to confirm your registration: http://www.concharto.com/member/confirm.htm?id=:confirmation 
            
    You can find out more about us at http://wiki.concharto.com/wiki/About.
            
    If you were not expecting this email, just ignore it, no further action is required to terminate the request.
     */
}

From source file:rescustomerservices.GmailQuickstart.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./* ww  w  .j a  v a  2s  .  co m*/
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

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

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

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:org.eclipse.ecr.automation.core.mail.Mailer.java

/**
 * Send a single email.//from  w w  w . j a  va 2s.c  om
 */
public void sendEmail(String from, String to, String subject, String body) throws MessagingException {
    // Here, no Authenticator argument is used (it is null).
    // Authenticators are used to prompt the user for user
    // name and password.
    MimeMessage message = new MimeMessage(getSession());
    // the "from" address may be set in code, or set in the
    // config file under "mail.from" ; here, the latter style is used
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(body);
    Transport.send(message);
}

From source file:it.geosolutions.geobatch.mail.SendMailAction.java

public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {
    final Queue<EventObject> ret = new LinkedList<EventObject>();

    while (events.size() > 0) {
        final EventObject ev;
        try {//w  ww .j av  a2 s.c  om
            if ((ev = events.remove()) != null) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Send Mail action.execute(): working on incoming event: " + ev.getSource());
                }

                File mail = (File) ev.getSource();

                FileInputStream fis = new FileInputStream(mail);
                String kmlURL = IOUtils.toString(fis);

                // /////////////////////////////////////////////
                // Send the mail with the given KML URL
                // /////////////////////////////////////////////

                // Recipient's email ID needs to be mentioned.
                String mailTo = conf.getMailToAddress();

                // Sender's email ID needs to be mentioned
                String mailFrom = conf.getMailFromAddress();

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

                // Setup mail server
                String mailSmtpAuth = conf.getMailSmtpAuth();
                properties.put("mail.smtp.auth", mailSmtpAuth);
                properties.put("mail.smtp.host", conf.getMailSmtpHost());
                properties.put("mail.smtp.starttls.enable", conf.getMailSmtpStarttlsEnable());
                properties.put("mail.smtp.port", conf.getMailSmtpPort());

                // Get the default Session object.
                final String mailAuthUsername = conf.getMailAuthUsername();
                final String mailAuthPassword = conf.getMailAuthPassword();

                Session session = Session.getDefaultInstance(properties,
                        (mailSmtpAuth.equalsIgnoreCase("true") ? new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mailAuthUsername, mailAuthPassword);
                            }
                        } : null));

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

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

                    // Set To: header field of the header.
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));

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

                    String mailHeaderName = conf.getMailHeaderName();
                    String mailHeaderValule = conf.getMailHeaderValue();
                    if (mailHeaderName != null && mailHeaderValule != null) {
                        message.addHeader(mailHeaderName, mailHeaderValule);
                    }

                    String mailMessageText = conf.getMailContentHeader();

                    message.setText(mailMessageText + "\n\n" + kmlURL);

                    // Send message
                    Transport.send(message);

                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("Sent message successfully....");

                } catch (MessagingException exc) {
                    ActionExceptionHandler.handleError(conf, this, "An error occurrd when sent message ...");
                    continue;
                }
            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Send Mail action.execute(): Encountered a NULL event: SKIPPING...");
                }
                continue;
            }
        } catch (Exception ioe) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Send Mail action.execute(): Unable to produce the output: ",
                        ioe.getLocalizedMessage(), ioe);
            }
            throw new ActionException(this, ioe.getLocalizedMessage(), ioe);
        }
    }

    return ret;
}

From source file:de.helmholtz_muenchen.ibis.utils.abstractNodes.HTExecutorNode.HTExecutorNodeModel.java

private void sendMail(String content) {

    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", emailhost);
    Session session = Session.getDefaultInstance(properties);

    try {/* www .  j  a v a  2s  .c  o m*/
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emailsender));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject(HEADER);
        message.setText(content);
        Transport.send(message);
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}

From source file:org.cloudcoder.healthmonitor.HealthMonitor.java

private void sendEmail(Map<String, Info> infoMap, List<ReportItem> reportItems, boolean goodNews,
        boolean badNews, String reportEmailAddress) throws MessagingException, AddressException {
    Session session = createMailSession(config);

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(reportEmailAddress));
    message.addRecipient(RecipientType.TO, new InternetAddress(reportEmailAddress));
    message.setSubject("CloudCoder health monitor report");

    StringBuilder body = new StringBuilder();
    body.append("<h1>CloudCoder health monitor report</h1>\n");

    if (badNews) {
        body.append("<h2>Unhealthy instances</h2>\n");
        body.append("<ul>\n");
        for (ReportItem item : reportItems) {
            if (item.badNews()) {
                appendReportItem(body, item, infoMap);
            }//from  ww w. ja  v a  2 s .com
        }
        body.append("</ul>\n");
    }

    if (goodNews) {
        body.append("<h2>Healthy instances (back on line)</h2>\n");
        body.append("<ul>\n");
        for (ReportItem item : reportItems) {
            if (item.goodNews()) {
                appendReportItem(body, item, infoMap);
            }
        }
        body.append("</ul>\n");
    }

    message.setContent(body.toString(), "text/html");

    Transport.send(message);
}