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) throws AddressException 

Source Link

Document

Parse the given comma separated sequence of addresses into InternetAddress objects.

Usage

From source file:com.gazbert.bxbot.core.mail.EmailAlerter.java

public void sendMessage(String subject, String msgContent) {

    if (sendEmailAlertsEnabled) {

        final Session session = Session.getInstance(smtpProps, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpConfig.getAccountUsername(),
                        smtpConfig.getAccountPassword());
            }//from w w w .j a  v  a  2s. c o  m
        });

        try {
            final Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(smtpConfig.getFromAddress()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(smtpConfig.getToAddress()));
            message.setSubject(subject);
            message.setText(msgContent);

            LOG.info(() -> "About to send following Email Alert with message content: " + msgContent);
            Transport.send(message);

        } catch (MessagingException e) {
            // not much we can do here, especially if the alert was critical - the bot is shutting down; just log it.
            LOG.error("Failed to send Email Alert. Details: " + e.getMessage(), e);
        }
    } else {
        LOG.warn("Email Alerts are disabled. Not sending the following message: Subject: " + subject
                + " Content: " + msgContent);
    }
}

From source file:com.googlecode.psiprobe.tools.Mailer.java

private MimeMessage createMimeMessage(Session session, MailMessage mailMessage) throws MessagingException {
    InternetAddress[] to = createAddresses(mailMessage.getToArray());
    InternetAddress[] cc = createAddresses(mailMessage.getCcArray());
    InternetAddress[] bcc = createAddresses(mailMessage.getBccArray());
    if (to.length == 0) {
        to = InternetAddress.parse(defaultTo);
    }//from   w  w  w. ja  v  a 2  s  .  c  o m

    String subject = mailMessage.getSubject();
    if (subjectPrefix != null && !subjectPrefix.equals("")) {
        subject = subjectPrefix + " " + subject;
    }

    MimeMultipart content = new MimeMultipart("related");

    //Create attachments
    DataSource[] attachments = mailMessage.getAttachmentsArray();
    for (int i = 0; i < attachments.length; i++) {
        DataSource attachment = attachments[i];
        MimeBodyPart attachmentPart = createAttachmentPart(attachment);
        content.addBodyPart(attachmentPart);
    }

    //Create message body
    MimeBodyPart bodyPart = createMessageBodyPart(mailMessage.getBody(), mailMessage.isBodyHtml());
    content.addBodyPart(bodyPart);

    MimeMessage message = new MimeMessage(session);
    if (from == null) {
        message.setFrom(); //Uses mail.from property
    } else {
        message.setFrom(new InternetAddress(from));
    }
    message.setRecipients(Message.RecipientType.TO, to);
    message.setRecipients(Message.RecipientType.CC, cc);
    message.setRecipients(Message.RecipientType.BCC, bcc);
    message.setSubject(subject);
    message.setContent(content);
    return message;
}

From source file:NotificationMessage.java

static void sendMail(String toUser, Severity s) {
    // Recipient's email ID needs to be mentioned.
    //String to = "abhiyank@gmail.com";//change accordingly

    // Sender's email ID needs to be mentioned
    String from = "mdtprojectteam16@gmail.com";//change accordingly
    final String username = "mdtprojectteam16";//change accordingly
    final String password = "mdtProject16";//change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from ww  w  .  java  2 s  .c  om*/
    });

    try {
        // Create a default MimeMessage object.
        javax.mail.Message message1 = new MimeMessage(session);

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

        // Set To: header field of the header.
        message1.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));

        // Set Subject: header field
        message1.setSubject("Alert Message From Patient");

        // Now set the actual message
        message1.setText(messageMap.get(s));

        // Send message
        Transport.send(message1);

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

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * Parses the adresslist./*www  . j  a va 2s  . c o m*/
 * 
 * @param addresslist
 * @param charset
 * @return
 */
public static InternetAddress[] parseInternetAddress(String addresslist, String charset)
        throws MessagingException {

    if (addresslist != null) {
        addresslist = addresslist.replace(';', ',');
        InternetAddress[] addressArray = InternetAddress.parse(addresslist);

        if (addressArray != null) {
            for (InternetAddress address : addressArray) {
                String personal = address.getPersonal();
                if (personal != null) {
                    try {
                        address.setPersonal(personal, charset);
                    } catch (UnsupportedEncodingException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }

        return addressArray;
    }

    return null;
}

From source file:io.kamax.mxisd.threepid.connector.email.EmailSmtpConnector.java

@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - "
                + "You must set a value for notifications to work");
    }/*from  www  .j  a  v  a  2 s .com*/

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));
        msg.setHeader("X-Mailer", "mxisd"); // FIXME set version
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(cfg.getTls() > 0);
        transport.setRequireStartTLS(cfg.getTls() > 1);

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword());
        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}

From source file:org.geoserver.wps.mail.SendMail.java

/**
 * Send an EMail to a specified address.
 * /*w  ww  . j  a va 2  s . c o m*/
 * @param address the to address
 * @param subject the email address
 * @param body message to send
 * @throws MessagingException the messaging exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void send(String address, String subject, String body) {
    try {
        // Session session = Session.getDefaultInstance(props, null);
        Session session = Session.getDefaultInstance(props,
                (conf.getMailSmtpAuth().equalsIgnoreCase("true") ? new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(conf.getUserName(), conf.getPassword());
                    }
                } : null));

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(conf.getFromAddress(), conf.getFromAddressname()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address));
        message.setSubject(subject);
        message.setText(body.toString());

        Transport.send(message);

    } catch (Exception e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }

}

From source file:org.hyperic.hq.ui.action.resource.common.monitor.alerts.config.AddOthersForm.java

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    if (!shouldValidate(mapping, request))
        return null;

    log.debug("validating email addresses: " + emailAddresses);
    ActionErrors errs = super.validate(mapping, request);
    if (null == errs && (emailAddresses == null || emailAddresses.length() == 0)) {
        // A special case, BaseValidatorForm will return null if Ok is
        // clicked and input is null, indicating a PrepareForm
        // action is occurring. This is tricky. However, it also
        // returns null if no validations failed. This is really
        // lame, in my opinion.
        return null;
    } else {//from w  ww .j a v  a  2s .c  o m
        errs = new ActionErrors();
    }

    try {
        InternetAddress[] addresses = InternetAddress.parse(emailAddresses);
    } catch (AddressException e) {
        if (e.getRef() == null) {
            ActionMessage err = new ActionMessage("alert.config.error.InvalidEmailAddresses", e.getMessage());
            errs.add("emailAddresses", err);
        } else {
            ActionMessage err = new ActionMessage("alert.config.error.InvalidEmailAddress", e.getRef(),
                    e.getMessage());
            errs.add("emailAddresses", err);
        }
    }

    return errs;
}

From source file:com.freemarker.mail.GMail.java

public boolean sendMailUsingJavaMailAPI(String to, String message1, HttpServletRequest req, String mid,
        String createdby, String pname, String mname) {
    String FinalMessage = new FreeMarkerMailTemplateCreater().createAndReturnTemplateDataMapping(message1,
            getTemplateLocation(req), mid, createdby, pname, mname);
    String from = "analytixdstest@gmail.com";
    final String username = "analytixdstest@gmail.com";
    final String password = "analytix000";
    String host = "smtp.gmail.com";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from   w ww. j  av  a2  s .  c o  m
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setContent(FinalMessage, "text/html; charset=utf-8");
        message.saveChanges();
        message.setSubject("Analytix Test Mail");
        Transport.send(message);
        return true;
    } catch (MessagingException e) {
        return false;

    }
}

From source file:fr.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java

public void prepare(MimeMessage message) throws Exception {

    // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369
    if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) {
        message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");
    }// ww w  .  j a  v  a2 s .  c  om

    if (getFrom() != null) {
        List<InternetAddress> toAddress = new ArrayList<InternetAddress>();
        toAddress.add(new InternetAddress(getFrom(), getFromName()));
        message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()]));
    }
    if (getTo() != null) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
    }
    if (getCc() != null) {
        message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc()));
    }
    if (getSubject() != null) {
        message.setSubject(getSubject());
    }

    MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
    message.setContent(mimeMultipart);

    if (getPlainTextContent() != null) {
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(getPlainTextContent(), "text/plain");
        mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(getHtmlContent(), "text/html");
        mimeMultipart.addBodyPart(htmlBodyPart);
    }

}

From source file:com.adaptris.mail.MailSenderImp.java

@Override
public void addTo(String address) throws MailException {
    try {/*from w ww .j  av  a 2  s .  co m*/
        addTo(InternetAddress.parse(address));
    } catch (AddressException e) {
        throw new MailException(e);
    }
}