Example usage for javax.mail.internet InternetAddress setAddress

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

Introduction

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

Prototype

public void setAddress(String address) 

Source Link

Document

Set the email address.

Usage

From source file:edu.stanford.muse.index.EmailDocument.java

private static void maskEmailDomain(Address[] addrs, AddressBook ab) {
    if (addrs != null) {
        for (Address a : addrs) {
            if (a instanceof InternetAddress) {
                InternetAddress i = (InternetAddress) a;
                i.setAddress(ab.getMaskedEmail(i.getAddress()));
            }/*from   w ww.j av a2  s  .co m*/
        }
    }
}

From source file:org.tsm.concharto.web.feedback.FeedbackController.java

public MimeMessage makeFeedbackMessage(MimeMessage message, FeedbackForm feedbackForm,
        HttpServletRequest request) {//from   w  w w  .  j a  v  a 2 s  .c o m

    //prepare the user info
    String requestInfo = getBrowserInfo(request);

    StringBuffer messageText = new StringBuffer(feedbackForm.getBody())
            .append("\n\n=============================================================\n").append(requestInfo);

    InternetAddress from = new InternetAddress();
    from.setAddress(feedbackForm.getEmail());
    InternetAddress to = new InternetAddress();
    to.setAddress(sendFeedbackToAddress);
    try {
        from.setPersonal(feedbackForm.getName());
        message.addRecipient(Message.RecipientType.TO, to);
        message.setSubject(FEEDBACK_SUBJECT + feedbackForm.getSubject());
        message.setText(messageText.toString());
        message.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
    } catch (MessagingException e) {
        log.error(e);
    }
    return message;
}

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());// w w w  .j  a  v  a 2 s  . 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:com.enonic.esl.net.Mail.java

/**
 * <p/> Send the mail. The SMTP host is contacted and the mail is sent according to the parameters set. </p> <p/> If it fails, it is
 * considered a runtime exception. Note that this doesn't make it very failsafe, so care should be taken when one wants fault tolerance.
 * One solution could be to catch the exception thrown. Another solution could be to use the JavaMail API directly. </p>
 *///from  ww  w.  j av a2 s  .c om
public void send() throws ESLException {
    // smtp server
    Properties smtpProperties = new Properties();
    if (smtpHost != null) {
        smtpProperties.put("mail.smtp.host", smtpHost);
        System.setProperty("mail.smtp.host", smtpHost);
    } else {
        smtpProperties.put("mail.smtp.host", DEFAULT_SMTPHOST);
        System.setProperty("mail.smtp.host", DEFAULT_SMTPHOST);
    }
    Session session = Session.getDefaultInstance(smtpProperties, null);

    try {
        // create message
        Message msg = new MimeMessage(session);
        // set from address
        InternetAddress addressFrom = new InternetAddress();
        if (from_email != null) {
            addressFrom.setAddress(from_email);
        }
        if (from_name != null) {
            addressFrom.setPersonal(from_name, ENCODING);
        }
        ((MimeMessage) msg).setFrom(addressFrom);

        if ((to.size() == 0 && bcc.size() == 0) || subject == null
                || (message == null && htmlMessage == null)) {
            LOG.error("Missing data. Unable to send mail.");
            throw new ESLException("Missing data. Unable to send mail.");
        }

        // set to:
        for (int i = 0; i < to.size(); ++i) {
            String[] recipient = to.get(i);
            InternetAddress addressTo = new InternetAddress(recipient[1]);
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.TO, addressTo);
        }

        // set bcc:
        for (int i = 0; i < bcc.size(); ++i) {
            String[] recipient = bcc.get(i);
            InternetAddress addressTo = null;
            try {
                addressTo = new InternetAddress(recipient[1]);
            } catch (Exception e) {
                System.err.println("exception on address: " + recipient[1]);
                continue;
            }
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.BCC, addressTo);
        }

        // set cc:
        for (int i = 0; i < cc.size(); ++i) {
            String[] recipient = cc.get(i);
            InternetAddress addressTo = new InternetAddress(recipient[1]);
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.CC, addressTo);
        }

        // Setting subject and content type
        ((MimeMessage) msg).setSubject(subject, ENCODING);

        if (message != null) {
            message = RegexpUtil.substituteAll("\\\\n", "\n", message);
        }

        // if there are any attachments, treat this as a multipart message.
        if (attachments.size() > 0) {
            BodyPart messageBodyPart = new MimeBodyPart();
            if (message != null) {
                ((MimeBodyPart) messageBodyPart).setText(message, ENCODING);
            } else {
                DataHandler dataHandler = new DataHandler(
                        new ByteArrayDataSource(htmlMessage, "text/html", ENCODING));
                ((MimeBodyPart) messageBodyPart).setDataHandler(dataHandler);
            }
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // add all attachments
            for (int i = 0; i < attachments.size(); ++i) {
                Object obj = attachments.get(i);
                if (obj instanceof String) {
                    System.err.println("attachment is String");
                    messageBodyPart = new MimeBodyPart();
                    ((MimeBodyPart) messageBodyPart).setText((String) obj, ENCODING);
                    multipart.addBodyPart(messageBodyPart);
                } else if (obj instanceof File) {
                    messageBodyPart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource((File) obj);
                    messageBodyPart.setDataHandler(new DataHandler(fds));
                    messageBodyPart.setFileName(fds.getName());
                    multipart.addBodyPart(messageBodyPart);
                } else if (obj instanceof FileItem) {
                    FileItem fileItem = (FileItem) obj;
                    messageBodyPart = new MimeBodyPart();
                    FileItemDataSource fds = new FileItemDataSource(fileItem);
                    messageBodyPart.setDataHandler(new DataHandler(fds));
                    messageBodyPart.setFileName(fds.getName());
                    multipart.addBodyPart(messageBodyPart);
                } else {
                    // byte array
                    messageBodyPart = new MimeBodyPart();
                    ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) obj, "text/html", ENCODING);
                    messageBodyPart.setDataHandler(new DataHandler(bads));
                    messageBodyPart.setFileName(bads.getName());
                    multipart.addBodyPart(messageBodyPart);
                }
            }

            msg.setContent(multipart);
        } else {
            if (message != null) {
                ((MimeMessage) msg).setText(message, ENCODING);
            } else {
                DataHandler dataHandler = new DataHandler(
                        new ByteArrayDataSource(htmlMessage, "text/html", ENCODING));
                ((MimeMessage) msg).setDataHandler(dataHandler);
            }
        }

        // send message
        Transport.send(msg);
    } catch (AddressException e) {
        String MESSAGE_30 = "Error in email address: " + e.getMessage();
        LOG.warn(MESSAGE_30);
        throw new ESLException(MESSAGE_30, e);
    } catch (UnsupportedEncodingException e) {
        String MESSAGE_40 = "Unsupported encoding: " + e.getMessage();
        LOG.error(MESSAGE_40, e);
        throw new ESLException(MESSAGE_40, e);
    } catch (SendFailedException sfe) {
        Throwable t = null;
        Exception e = sfe.getNextException();
        while (e != null) {
            t = e;
            if (t instanceof SendFailedException) {
                e = ((SendFailedException) e).getNextException();
            } else {
                e = null;
            }
        }
        if (t != null) {
            String MESSAGE_50 = "Error sending mail: " + t.getMessage();
            throw new ESLException(MESSAGE_50, t);
        } else {
            String MESSAGE_50 = "Error sending mail: " + sfe.getMessage();
            throw new ESLException(MESSAGE_50, sfe);
        }
    } catch (MessagingException e) {
        String MESSAGE_50 = "Error sending mail: " + e.getMessage();
        LOG.error(MESSAGE_50, e);
        throw new ESLException(MESSAGE_50, e);
    }
}

From source file:edu.stanford.muse.email.EmailFetcherStats.java

/**
 * intern a bunch of addrs, to save memory
 *
 * @throws UnsupportedEncodingException/*w w  w  .  j a  v a2 s.  c  om*/
 */
private static void internAddressList(Address[] addrs) throws UnsupportedEncodingException {
    if (addrs == null)
        return;

    for (Address a : addrs) {
        if (a instanceof InternetAddress) {
            InternetAddress ia = (InternetAddress) a;
            String address = ia.getAddress(), personal = ia.getPersonal();
            if (address != null)
                ia.setAddress(InternTable.intern(address));
            if (personal != null)
                ia.setPersonal(InternTable.intern(personal));
        }
    }
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist.
 *
 * Json sent should have following keys :
 *
 * - to      : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"]
 * - cc      : json array of email to 'CC' email ex: ["him@rm.fr"]
 * - bcc     : json array of email to add recipient as blind CC ["secret@rm.fr"]
 * - subject : subject of email/*from w  w  w  .ja va2  s  .  c o m*/
 * - body    : Body of email
 *
 * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory.
 *
 * complete json example :
 *
 * {
 *   "to": ["you@rm.fr", "another-guy@rm.fr"],
 *   "cc": ["him@rm.fr"],
 *   "bcc": ["secret@rm.fr"],
 *   "subject": "test email",
 *   "body": "Hi, this a test EMail, please do not reply."
 * }
 *
 */
@RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json")
@ResponseBody
public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request)
        throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException {

    JSONObject payload = new JSONObject(rawRequest);
    InternetAddress[] to = this.populateRecipient("to", payload);
    InternetAddress[] cc = this.populateRecipient("cc", payload);
    InternetAddress[] bcc = this.populateRecipient("bcc", payload);

    this.checkSubject(payload);
    this.checkBody(payload);
    this.checkRecipient(to, cc, bcc);

    LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to="
            + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc="
            + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles"));

    LOG.debug("EMail request : " + payload.toString());

    // Instanciate MimeMessage
    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    MimeMessage message = new MimeMessage(session);

    // Generate From header
    InternetAddress from = new InternetAddress();
    from.setAddress(this.georConfig.getProperty("emailProxyFromAddress"));
    from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setFrom(from);

    // Generate Reply-to header
    InternetAddress replyTo = new InternetAddress();
    replyTo.setAddress(request.getHeader("sec-email"));
    replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setReplyTo(new Address[] { replyTo });

    // Generate to, cc and bcc headers
    if (to.length > 0)
        message.setRecipients(Message.RecipientType.TO, to);
    if (cc.length > 0)
        message.setRecipients(Message.RecipientType.CC, cc);
    if (bcc.length > 0)
        message.setRecipients(Message.RecipientType.BCC, bcc);

    // Add subject and body
    message.setSubject(payload.getString("subject"), "UTF-8");
    message.setText(payload.getString("body"), "UTF-8", "plain");
    message.setSentDate(new Date());

    // finally send message
    Transport.send(message);

    JSONObject res = new JSONObject();
    res.put("success", true);
    return res.toString();
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Create an java String list based on json array found in json ojbect
 *
 * @param field field name where to find json array to parse
 * @param request full object where to search for key
 * @return java list of extracted values
 *///from   w w  w. ja  v a  2  s  .c o  m
private InternetAddress[] populateRecipient(String field, JSONObject request)
        throws JSONException, AddressException {
    List<InternetAddress> res = new LinkedList<InternetAddress>();
    if (request.has(field)) {
        JSONArray rawTo = request.getJSONArray(field);
        for (int i = 0; i < rawTo.length(); i++) {
            InternetAddress to = new InternetAddress();
            to.setAddress(rawTo.getString(i));
            to.validate();
            res.add(to);
        }
    }
    return res.toArray(new InternetAddress[res.size()]);
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist.
 *
 * Json sent should have following keys :
 *
 * - to      : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"]
 * - cc      : json array of email to 'CC' email ex: ["him@rm.fr"]
 * - bcc     : json array of email to add recipient as blind CC ["secret@rm.fr"]
 * - subject : subject of email//from   ww  w  . j a  v  a  2 s  .  com
 * - body    : Body of email
 *
 * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory.
 *
 * complete json example :
 *
 * {
 *   "to": ["you@rm.fr", "another-guy@rm.fr"],
 *   "cc": ["him@rm.fr"],
 *   "bcc": ["secret@rm.fr"],
 *   "subject": "test email",
 *   "body": "Hi, this a test EMail, please do not reply."
 * }
 *
 */
@RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json")
@ResponseBody
public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request)
        throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException {

    JSONObject payload = new JSONObject(rawRequest);
    InternetAddress[] to = this.populateRecipient("to", payload);
    InternetAddress[] cc = this.populateRecipient("cc", payload);
    InternetAddress[] bcc = this.populateRecipient("bcc", payload);

    this.checkSubject(payload);
    this.checkBody(payload);
    this.checkRecipient(to, cc, bcc);

    LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to="
            + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc="
            + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles"));

    LOG.debug("EMail request : " + payload.toString());

    // Instanciate MimeMessage
    Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());
    Session session = Session.getInstance(props, null);
    MimeMessage message = new MimeMessage(session);

    // Generate From header
    InternetAddress from = new InternetAddress();
    from.setAddress(this.georConfig.getProperty("emailProxyFromAddress"));
    from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setFrom(from);

    // Generate Reply-to header
    InternetAddress replyTo = new InternetAddress();
    replyTo.setAddress(request.getHeader("sec-email"));
    replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setReplyTo(new Address[] { replyTo });

    // Generate to, cc and bcc headers
    if (to.length > 0)
        message.setRecipients(Message.RecipientType.TO, to);
    if (cc.length > 0)
        message.setRecipients(Message.RecipientType.CC, cc);
    if (bcc.length > 0)
        message.setRecipients(Message.RecipientType.BCC, bcc);

    // Add subject and body
    message.setSubject(payload.getString("subject"), "UTF-8");
    message.setText(payload.getString("body"), "UTF-8", "plain");
    message.setSentDate(new Date());

    // finally send message
    Transport.send(message);

    JSONObject res = new JSONObject();
    res.put("success", true);
    return res.toString();
}

From source file:org.tsm.concharto.web.util.ConfirmationEmail.java

public static MimeMessage makeMessage(MimeMessage message, User user, String subject, String messageText) {
    InternetAddress from = new InternetAddress();
    from.setAddress(FROM_ADDRESS);
    InternetAddress to = new InternetAddress();
    to.setAddress(user.getEmail());/*w  w w. j a  va 2s  .  c o m*/
    try {
        from.setPersonal(FROM_NAME);
        message.addRecipient(Message.RecipientType.TO, to);
        message.setSubject(subject);
        message.setText(messageText);
        message.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
    } catch (MessagingException e) {
        log.error(e);
    }
    return message;
}

From source file:util.Check.java

/**
 * Checks if a string is a valid email address.
 * /*from   w  ww . j  av  a 2  s  . com*/
 * @param email
 * @return
 */
public boolean isEmail(final String email) {
    boolean check = false;
    try {
        final InternetAddress ia = new InternetAddress();
        ia.setAddress(email);
        try {
            ia.validate(); // throws an error for invalid addresses and null input, but does not catch all errors
            // we are using apache commons email validator
            final EmailValidator validator = EmailValidator.getInstance();
            check = validator.isValid(email);

            // EmailValidator is agnostic about valid domain names...
            // ...we do an additional check
            final Pattern p = Pattern.compile("@[a-z0-9-]+(\\.[a-z0-9-]+)*\\"
                    + ".([a-z]{2}|aero|arpa|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|nato|net|"
                    + "org|pro|tel|travel|xxx)$\\b");
            // we need to match against lower case for the above regex
            final Matcher m = p.matcher(email.toLowerCase());
            if (!m.find()) {
                // reset to false, if we do not have a match
                check = false;
            }

        } catch (final AddressException e1) {
            LOG.info("isEmail: " + email + " " + e1.toString());
        }
    } catch (final Exception e) {
        LOG.error("isEmail: " + email + " " + e.toString());
    }

    return check;
}