Example usage for javax.mail.internet InternetAddress parse

List of usage examples for javax.mail.internet InternetAddress parse

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress parse.

Prototype

public static InternetAddress[] parse(String addresslist, boolean strict) throws AddressException 

Source Link

Document

Parse the given sequence of addresses into InternetAddress objects.

Usage

From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java

@Override
public void send(final MailToSend mail) {
    SmtpConfiguration smtpConfiguration = SmtpConfiguration.fromDefaultSettings();

    MailAddress fromMailAddress = mail.getFrom();
    Session session = getMailSession(smtpConfiguration);
    try {/*from  w  w  w  . j ava2s.c  o m*/
        InternetAddress fromAddress = fromMailAddress.getAuthorizedInternetAddress();
        InternetAddress replyToAddress = null;
        List<InternetAddress[]> toAddresses = new ArrayList<>();

        // Parsing destination address for compliance with RFC822.
        final Collection<ReceiverMailAddressSet> addressBatches = mail.getTo().getBatchedReceiversList();
        for (ReceiverMailAddressSet addressBatch : addressBatches) {
            try {
                toAddresses.add(InternetAddress.parse(addressBatch.getEmailsSeparatedByComma(), false));
            } catch (AddressException e) {
                SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE",
                        "From = " + fromMailAddress + ", To = " + addressBatch.getEmailsSeparatedByComma(), e);
            }
        }
        try {
            if (mail.isReplyToRequired()) {
                replyToAddress = new InternetAddress(fromMailAddress.getEmail(), false);
                if (StringUtil.isDefined(fromMailAddress.getName())) {
                    replyToAddress.setPersonal(fromMailAddress.getName(), Charsets.UTF_8.name());
                }
            }
        } catch (AddressException e) {
            SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE",
                    "ReplyTo = " + fromMailAddress + " is malformed.", e);
        }
        MimeMessage email = new MimeMessage(session);
        email.setFrom(fromAddress);
        if (replyToAddress != null) {
            email.setReplyTo(new InternetAddress[] { replyToAddress });
        }
        email.setHeader("Precedence", "list");
        email.setHeader("List-ID", fromAddress.getAddress());
        email.setSentDate(new Date());
        email.setSubject(mail.getSubject(), CharEncoding.UTF_8);
        mail.getContent().applyOn(email);

        // Sending.
        performSend(mail, smtpConfiguration, session, email, toAddresses);

    } catch (MessagingException | UnsupportedEncodingException e) {
        SilverLogger.getLogger(this).error(e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nuxeo.ecm.platform.ec.notification.email.EmailHelper.java

protected void sendmail0(Map<String, Object> mail)
        throws MessagingException, IOException, TemplateException, LoginException, RenderingException {

    Session session = getSession();/*from   w w  w. j a  v a 2s.  c  o m*/
    if (javaMailNotAvailable || session == null) {
        log.warn("Not sending email since JavaMail is not configured");
        return;
    }

    // Construct a MimeMessage
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(session.getProperty("mail.from")));
    Object to = mail.get("mail.to");
    if (!(to instanceof String)) {
        log.error("Invalid email recipient: " + to);
        return;
    }
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) to, false));

    RenderingService rs = Framework.getService(RenderingService.class);

    DocumentRenderingContext context = new DocumentRenderingContext();
    context.remove("doc");
    context.putAll(mail);
    context.setDocument((DocumentModel) mail.get("document"));
    context.put("Runtime", Framework.getRuntime());

    String customSubjectTemplate = (String) mail.get(NotificationConstants.SUBJECT_TEMPLATE_KEY);
    if (customSubjectTemplate == null) {
        String subjTemplate = (String) mail.get(NotificationConstants.SUBJECT_KEY);
        Template templ = new Template("name", new StringReader(subjTemplate), stringCfg);

        Writer out = new StringWriter();
        templ.process(mail, out);
        out.flush();

        msg.setSubject(out.toString(), "UTF-8");
    } else {
        rs.registerEngine(new NotificationsRenderingEngine(customSubjectTemplate));

        LoginContext lc = Framework.login();

        Collection<RenderingResult> results = rs.process(context);
        String subjectMail = "<HTML><P>No parsing Succeded !!!</P></HTML>";

        for (RenderingResult result : results) {
            subjectMail = (String) result.getOutcome();
        }
        subjectMail = NotificationServiceHelper.getNotificationService().getEMailSubjectPrefix() + subjectMail;
        msg.setSubject(subjectMail, "UTF-8");

        lc.logout();
    }

    msg.setSentDate(new Date());

    rs.registerEngine(new NotificationsRenderingEngine((String) mail.get(NotificationConstants.TEMPLATE_KEY)));

    LoginContext lc = Framework.login();

    Collection<RenderingResult> results = rs.process(context);
    String bodyMail = "<HTML><P>No parsing Succedeed !!!</P></HTML>";

    for (RenderingResult result : results) {
        bodyMail = (String) result.getOutcome();
    }

    lc.logout();

    rs.unregisterEngine("ftl");

    msg.setContent(bodyMail, "text/html; charset=utf-8");

    // Send the message.
    Transport.send(msg);
}

From source file:com.emc.plants.service.impl.MailerBean.java

/** 
 * Create a mail message and send it./*from w  w w . j ava2  s .  c  om*/
 *
 * @param customerInfo  Customer information.
 * @param orderKey
 * @throws MailerAppException
 */
public void createAndSendMail(CustomerInfo customerInfo, long orderKey) throws MailerAppException {
    try {
        EMailMessage eMessage = new EMailMessage(createSubjectLine(orderKey), createMessage(orderKey),
                customerInfo.getCustomerID());
        Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: "
                + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents());

        //Session mailSession = (Session) Util.getInitialContext().lookup(MAIL_SESSION);

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMessage.getEmailReceiver(), false));

        msg.setSubject(eMessage.getSubject());
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setText(eMessage.getHtmlContents(), "us-ascii");
        msg.setHeader("X-Mailer", "JavaMailer");
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        Transport.send(msg);

        Util.debug("\nMail sent successfully.");
    } catch (Exception e) {
        Util.debug("Error sending mail. Have mail resources been configured correctly?");
        Util.debug("createAndSendMail exception : " + e);
        e.printStackTrace();
        throw new MailerAppException("Failure while sending mail");
    }
}

From source file:io.mapzone.arena.EMailHelpDashlet.java

protected void send() throws Exception {
    msg.addRecipients(RecipientType.TO, InternetAddress.parse(to.get(), false));
    msg.setSentDate(new Date());
    Transport.send(msg);//from w  w w .  j a  v a2  s.c  o  m
}

From source file:Interface.FoodDistributionWorkArea.FoodDistributionWorkArea.java

public void sendEmail(String emailID, Food food) {

    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    final String username = "kunal.deora@gmail.com";//
    final String password = "adrika46";
    String text = "Hi Sir/Mam, " + '\n'
            + "You have received rewards points for the food you have donated. Details are listed below: "
            + '\n' + "Food Name:  " + food.getFoodName() + '\n' + "Food ID :" + food.getFoodBarCode() + '\n'
            + "Food Reward Points " + food.getRewardPoints() + '\n'
            + "If you have any queries you can contact us on +133333333333" + '\n'
            + "Thank you for helping for the betterment of society. Every little bite counts :) " + '\n';
    try {/*from   ww  w  .j  av a2  s.  c o  m*/
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(username, password);
            }
        });

        // -- Create a new message --
        javax.mail.Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress("kunal.deora@gmail.com"));
        msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(emailID, false));
        msg.setSubject("Congratulations! You have received reward points !!!");
        msg.setText(text);
        msg.setSentDate(new Date());
        javax.mail.Transport.send(msg);
        System.out.println("Message sent.");
    } catch (javax.mail.MessagingException e) {
        System.out.println("Erreur d'envoi, cause: " + e);
    }

}

From source file:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailFactory.java

private InternetAddress getReplyToAddressFromConfig(ServletContext ctx) {
    ConfigurationProperties config = ConfigurationProperties.getBean(ctx);
    String rawAddress = config.getProperty(REPLY_TO_PROPERTY, "");
    if (rawAddress.isEmpty()) {
        throw new NotConfiguredException(REPLY_TO_PROPERTY);
    }//  w w w  .  j a  va  2 s  .  c  o  m

    try {
        InternetAddress[] addresses = InternetAddress.parse(rawAddress, false);
        if (addresses.length == 0) {
            throw new BadPropertyValueException("No Reply-To address", REPLY_TO_PROPERTY);
        } else if (addresses.length > 1) {
            throw new BadPropertyValueException("More than one Reply-To address", REPLY_TO_PROPERTY);
        } else {
            return addresses[0];
        }
    } catch (AddressException e) {
        throw new IllegalStateException(
                "Error while parsing Reply-To address configured in '" + REPLY_TO_PROPERTY + "'", e);
    }
}

From source file:com.reizes.shiva.net.mail.Mail.java

public void sendHtmlMail(String fromName, String from, String to, String cc, String bcc, String subject,
        String content) throws UnsupportedEncodingException, MessagingException {
    boolean parseStrict = false;
    MimeMessage message = new MimeMessage(getSessoin());
    InternetAddress address = InternetAddress.parse(from, parseStrict)[0];

    if (fromName != null) {
        address.setPersonal(fromName, charset);
    }/*from   w  w w  .ja  v  a2s  .  c o  m*/

    message.setFrom(address);

    message.setRecipients(Message.RecipientType.TO, parseAddresses(to));

    if (cc != null) {
        message.setRecipients(Message.RecipientType.CC, parseAddresses(cc));
    }
    if (bcc != null) {
        message.setRecipients(Message.RecipientType.BCC, parseAddresses(bcc));
    }

    message.setSubject(subject, charset);

    message.setHeader("X-Mailer", "sendMessage");
    message.setSentDate(new java.util.Date()); //   

    Multipart multipart = new MimeMultipart();
    MimeBodyPart bodypart = new MimeBodyPart();
    bodypart.setContent(content, "text/html; charset=" + charset);
    multipart.addBodyPart(bodypart);

    message.setContent(multipart);
    Transport.send(message);
}

From source file:com.flexive.shared.FxMailUtils.java

/**
 * Sends an email//from  ww w.  j  a  va  2  s.  c o m
 *
 * @param SMTPServer      IP Address of the SMTP server
 * @param subject         subject of the email
 * @param textBody        plain text
 * @param htmlBody        html text
 * @param to              recipient
 * @param cc              cc recepient
 * @param bcc             bcc recipient
 * @param from            sender
 * @param replyTo         reply-to address
 * @param mimeAttachments strings containing mime encoded attachments
 * @throws FxApplicationException on errors
 */
public static void sendMail(String SMTPServer, String subject, String textBody, String htmlBody, String to,
        String cc, String bcc, String from, String replyTo, String... mimeAttachments)
        throws FxApplicationException {

    try {
        // Set the mail server
        java.util.Properties properties = System.getProperties();
        if (SMTPServer != null)
            properties.put("mail.smtp.host", SMTPServer);

        // Get a session and create a new message
        javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
        MimeMessage msg = new MimeMessage(session);

        // Set the sender
        if (StringUtils.isBlank(from))
            msg.setFrom(); // Uses local IP Adress and the user under which the server is running
        else {
            msg.setFrom(createAddress(from));
        }

        if (!StringUtils.isBlank(replyTo))
            msg.setReplyTo(encodePersonal(InternetAddress.parse(replyTo, false)));

        // Set the To, Cc and Bcc fields
        if (!StringUtils.isBlank(to))
            msg.setRecipients(MimeMessage.RecipientType.TO, encodePersonal(InternetAddress.parse(to, false)));
        if (!StringUtils.isBlank(cc))
            msg.setRecipients(MimeMessage.RecipientType.CC, encodePersonal(InternetAddress.parse(cc, false)));
        if (!StringUtils.isBlank(bcc))
            msg.setRecipients(MimeMessage.RecipientType.BCC, encodePersonal(InternetAddress.parse(bcc, false)));

        // Set the subject
        msg.setSubject(subject, "UTF-8");

        String sMainType = "Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"";

        StringBuilder body = new StringBuilder(5000);

        if (mimeAttachments.length > 0) {
            sMainType = "Multipart/Mixed;\n\tboundary=\"" + BOUNDARY2 + "\"";
            body.append("This is a multi-part message in MIME format.\n\n");
            body.append("--" + BOUNDARY2 + "\n");
            body.append("Content-Type: Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"\n\n\n");
        }

        if (textBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/plain; charset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            body.append(encodeQuotedPrintable(textBody)).append("\n");
        }
        if (htmlBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/html;\n\tcharset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            if (htmlBody.toLowerCase().indexOf("<html>") < 0) {
                body.append("<HTML><HEAD>\n<TITLE></TITLE>\n");
                body.append(
                        "<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Dutf-8\"></HEAD>\n<BODY>\n");
                body.append(encodeQuotedPrintable(htmlBody)).append("</BODY></HTML>\n");
            } else
                body.append(encodeQuotedPrintable(htmlBody)).append("\n");
        }

        body.append("\n--" + BOUNDARY1 + "--\n");

        if (mimeAttachments.length > 0) {
            for (String mimeAttachment : mimeAttachments) {
                body.append("\n--" + BOUNDARY2 + "\n");
                body.append(mimeAttachment).append("\n");
            }
            body.append("\n--" + BOUNDARY2 + "--\n");
        }

        msg.setDataHandler(
                new javax.activation.DataHandler(new ByteArrayDataSource(body.toString(), sMainType)));

        // Set the header
        msg.setHeader("X-Mailer", "JavaMailer");

        // Set the sent date
        msg.setSentDate(new java.util.Date());

        // Send the message
        javax.mail.Transport.send(msg);
    } catch (AddressException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.address", e.getRef());
    } catch (javax.mail.MessagingException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (IOException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (EncoderException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    }
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.EmailTokenProvider.java

private void sendEmail(String sender, String recipient, String subject, String text) {
    try {//from  www .j a  v a2 s .co  m
        Properties props = System.getProperties();
        props.put("mail.smtp.port", "" + smtpPort);
        props.put("mail.smtp.socketFactory.port", "" + smtpPort);
        if (ssl) {
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.starttls.required", "true");
        }
        if (smtpUser != null) {
            props.put("mail.smtp.auth", "true");
        }

        Session session = Session.getInstance(props, null);

        final MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(sender));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
        msg.setSubject(subject);
        msg.setText(text, Constants.UTF_8);
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        t.connect(smtpHost, smtpUser, smtpPassword);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.blue.star.plugins.send_mail.java

public boolean execute_check() {

    Properties props = System.getProperties();
    props.put("mail.smtp.host", smtpServer);
    if (smtpAuth) {
        props.put("mail.smtp.auth", "true");
    }/*from w  ww.  ja  va2s.  c  o m*/

    Session session = Session.getInstance(props, null);
    SMTPTransport transport = null;
    //      if (debug)
    //         session.setDebug(true);

    // construct the message
    try {
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

        if (subject != null)
            msg.setSubject(subject);

        msg.setHeader("X-Mailer", "blue-send-mail");
        msg.setSentDate(new Date());
        msg.setText(message.replace("\\n", "\n").replace("\\t", "\t"));

        transport = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        if (smtpAuth)
            transport.connect(smtpServer, smtpUser, smtpPass);
        else
            transport.connect();
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

    } catch (MessagingException mE) {
        mE.printStackTrace();
        this.state = common_h.STATE_CRITICAL;
        this.text = mE.getMessage();
        return false;
    } finally {
        try {
            transport.close();
        } catch (Exception e) {
        }
    }

    state = common_h.STATE_OK;
    text = "Message Sent!";
    return true;
}