Example usage for javax.mail.internet InternetAddress InternetAddress

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

Introduction

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

Prototype

public InternetAddress(String address) throws AddressException 

Source Link

Document

Constructor.

Usage

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

protected void sendEmail(Email email, List<Email> successfulEmails) {
    try {// w  w w .  ja  va2 s  . com
        if (logger.isDebugEnabled()) {
            logger.debug("Attempting to send " + email.getId() + " " + email.getSubject());
            if (email.getTo() != null) {
                logger.debug("To: " + Arrays.toString(email.getTo().toArray()));
            } else {
                logger.debug("To is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("CC: " + Arrays.toString(email.getCc().toArray()));
            } else {
                logger.debug("CC is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("BCC: " + Arrays.toString(email.getBcc().toArray()));
            } else {
                logger.debug("BCC is NULL");
            }
            if (email.getTo() != null) {
                logger.debug("FROM: " + email.getFrom());
            } else {
                logger.debug("FROM is NULL");
            }
            if (email.getAttachments() != null) {
                logger.debug("Attachments: " + Arrays.toString(email.getAttachments().toArray()));
                for (Attachments attachment : email.getAttachments()) {
                    logger.debug("Attachment: " + attachment.getName());
                }
            } else {
                logger.debug("No attachments");
            }
        }
        //Send email
        if (StringUtils.isBlank(email.getSubject()) || StringUtils.isBlank(email.getFrom())) {
            logger.warn(new StringBuilder("Invalid email without either from or a subject, thus ignoring it ")
                    .append(email.getId()).toString());
            return;
        }
        MimeMessage message = new MimeMessage(session);
        message.setSubject(email.getSubject());
        message.setFrom(new InternetAddress(email.getFrom()));
        addRecipients(message, Message.RecipientType.TO, email.getTo());
        addRecipients(message, Message.RecipientType.CC, email.getCc());
        addRecipients(message, Message.RecipientType.BCC, email.getBcc());
        if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())
                && email.getMessage().getMsgType().equals(MsgType.PLAIN)
                && (email.getAttachments() == null || email.getAttachments().isEmpty())) {
            message.setText(email.getMessage().getMsgBody());
        } else {
            Multipart multipart = new MimeMultipart();
            if (email.getMessage() != null && StringUtils.isNotBlank(email.getMessage().getMsgBody())) {
                MimeBodyPart bodyPart = new MimeBodyPart();
                switch (email.getMessage().getMsgType()) {
                case HTML:
                    bodyPart.setContent(email.getMessage().getMsgBody(), "html");
                    break;
                case PLAIN:
                default:
                    bodyPart.setText(email.getMessage().getMsgBody());
                }
                multipart.addBodyPart(bodyPart);
            }
            if (email.getAttachments() != null && !email.getAttachments().isEmpty()) {
                for (Attachments attachment : email.getAttachments()) {
                    addAttachment(multipart, attachment);
                }
            }
            message.setContent(multipart);
        }
        Transport.send(message);
        if (logger.isDebugEnabled()) {
            logger.debug("Sent " + email.getId());
        }
        //Update status
        email.setMailStatus(Email.MailStatus.SENT);
        successfulEmails.add(email);
        if (logger.isDebugEnabled()) {
            logger.debug("Set new mail status and add to successful queue " + email.getSubject());
        }
    } catch (Exception ex) {
        logger.warn(
                new StringBuilder("Error sending email with subject ").append(email.getSubject()).toString(),
                ex);
    }
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {

    String contentType;//from   w  w  w.  j av  a2 s  .co  m
    String fileExtension;
    String nameSuffix;
    JobExecutionContext jobExecutionContext;

    logger.debug("IN");

    try {

        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        nameSuffix = dispatchContext.getNameSuffix();
        jobExecutionContext = dispatchContext.getJobExecutionContext();

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";

        int smptPort = 25;

        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");

        /*
        if( (user==null) || user.trim().equals(""))
           throw new Exception("Smtp user not configured");
                
        if( (pass==null) || pass.trim().equals(""))
           throw new Exception("Smtp password not configured");
        */

        String mailTos = "";
        List dlIds = dispatchContext.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(document, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        Session session = null;

        if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
            props.put("mail.smtp.auth", "false");
            session = Session.getInstance(props);
            logger.debug("Connecting to mail server without authentication");
        } else {
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SMTPAuthenticator(user, pass);
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }
            session = Session.getInstance(props, auth);
            logger.debug("Connecting to mail server with authentication");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = document.getName() + nameSuffix;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType,
                document.getName() + nameSuffix + fileExtension);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        //mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }

        if (jobExecutionContext.getNextFireTime() == null) {
            String triggername = jobExecutionContext.getTrigger().getName();
            dlIds = dispatchContext.getDlIds();
            it = dlIds.iterator();
            while (it.hasNext()) {
                Integer dlId = (Integer) it.next();
                DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);
                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                        (document.getId()).intValue(), triggername);
            }
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }

    return true;
}

From source file:com.mobileman.projecth.business.messages.MessageServiceTest.java

/**
 * /*from   w w  w. j  a va2  s .  com*/
 * @throws Exception
 */
@Test
public void replyToMessage() throws Exception {

    User pat1 = userService.findUserByLogin("sysuser1");
    assertNotNull(pat1);
    User pat2 = userService.findUserByLogin("sysuser2");
    assertNotNull(pat2);

    List<Message> messagesOld = messageService.findAll();
    Message replyToMessage = messagesOld.get(0);

    messageService.sendReplyToMessage(replyToMessage.getId(), "I am fine", true);

    List<Message> messages = messageService.findAll();
    assertEquals(messagesOld.size() + 1, messages.size());
    Message message = messages.get(messages.size() - 1);
    assertEquals(replyToMessage.getSender().getId(), message.getReceiver().getId());
    assertEquals(replyToMessage.getReceiver().getId(), message.getSender().getId());

    List<WiserMessage> mailMessages = wiser.getMessages();
    assertEquals(2, mailMessages.size());
    assertEquals(new InternetAddress("nachrichten@projecth.com"),
            mailMessages.get(0).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("pat1@projecth.com"),
            mailMessages.get(0).getMimeMessage().getRecipients(javax.mail.Message.RecipientType.TO)[0]);
    assertEquals("Hallo pat2", mailMessages.get(0).getMimeMessage().getSubject());

    assertEquals(new InternetAddress("nachrichten@projecth.com"),
            mailMessages.get(1).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("doc1@projecth.com"),
            mailMessages.get(1).getMimeMessage().getRecipients(javax.mail.Message.RecipientType.TO)[0]);
    assertEquals("Hallo pat2", mailMessages.get(1).getMimeMessage().getSubject());
}

From source file:org.jresponder.message.MessageRefImpl.java

/**
 * Render a message in the context of a particular subscriber
 * and subscription./*  ww  w  .j av  a  2 s.  c  om*/
 */
@Override
public boolean populateMessage(MimeMessage aMimeMessage, SendConfig aSendConfig, Subscriber aSubscriber,
        Subscription aSubscription) {

    try {

        // prepare context
        Map<String, Object> myRenderContext = new HashMap<String, Object>();
        myRenderContext.put("subscriber", aSubscriber);
        myRenderContext.put("subscription", aSubscription);
        myRenderContext.put("config", aSendConfig);
        myRenderContext.put("message", this);

        // render the whole file
        String myRenderedFileContents = TextRenderUtil.getInstance().render(fileContents, myRenderContext);

        // now parse again with Jsoup
        Document myDocument = Jsoup.parse(myRenderedFileContents);

        String myHtmlBody = "";
        String myTextBody = "";

        // html body
        Elements myBodyElements = myDocument.select("#htmlbody");
        if (!myBodyElements.isEmpty()) {
            myHtmlBody = myBodyElements.html();
        }

        // text body
        Elements myJrTextBodyElements = myDocument.select("#textbody");
        if (!myJrTextBodyElements.isEmpty()) {
            myTextBody = TextUtil.getInstance().getWholeText(myJrTextBodyElements.first());
        }

        // now build the actual message
        MimeMessage myMimeMessage = aMimeMessage;
        // wrap it in a MimeMessageHelper - since some things are easier with that
        MimeMessageHelper myMimeMessageHelper = new MimeMessageHelper(myMimeMessage);

        // set headers

        // subject
        myMimeMessageHelper.setSubject(TextRenderUtil.getInstance()
                .render((String) propMap.get(MessageRefProp.JR_SUBJECT.toString()), myRenderContext));

        // TODO: implement DKIM, figure out subetha

        String mySenderEmailPattern = aSendConfig.getSenderEmailPattern();
        String mySenderEmail = TextRenderUtil.getInstance().render(mySenderEmailPattern, myRenderContext);
        myMimeMessage.setSender(new InternetAddress(mySenderEmail));

        myMimeMessageHelper.setTo(aSubscriber.getEmail());

        // from
        myMimeMessageHelper.setFrom(
                TextRenderUtil.getInstance()
                        .render((String) propMap.get(MessageRefProp.JR_FROM_EMAIL.toString()), myRenderContext),
                TextRenderUtil.getInstance()
                        .render((String) propMap.get(MessageRefProp.JR_FROM_NAME.toString()), myRenderContext));

        // see how to set body

        // if we have both text and html, then do multipart
        if (myTextBody.trim().length() > 0 && myHtmlBody.trim().length() > 0) {

            // create wrapper multipart/alternative part
            MimeMultipart ma = new MimeMultipart("alternative");
            myMimeMessage.setContent(ma);
            // create the plain text
            BodyPart plainText = new MimeBodyPart();
            plainText.setText(myTextBody);
            ma.addBodyPart(plainText);
            // create the html part
            BodyPart html = new MimeBodyPart();
            html.setContent(myHtmlBody, "text/html");
            ma.addBodyPart(html);
        }

        // if only HTML, then just use that
        else if (myHtmlBody.trim().length() > 0) {
            myMimeMessageHelper.setText(myHtmlBody, true);
        }

        // if only text, then just use that
        else if (myTextBody.trim().length() > 0) {
            myMimeMessageHelper.setText(myTextBody, false);
        }

        // if neither text nor HTML, then the message is being skipped,
        // so we just return null
        else {
            return false;
        }

        return true;

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

}

From source file:com.iana.dver.controller.RegistrationController.java

private void sendRegDetailEmail(DverUserVO dverUserVO, DverUserLoginVO dverUserLoginVO,
        DverConfigVO dverConfigVO) throws IOException, DocumentException, AddressException {

    logger.info("Send Registration Email.....");
    try {/*  w  w w . j a  v  a  2  s  .  c  o  m*/
        PdfReader reader = new PdfReader(
                servletContext.getResourceAsStream("/WEB-INF/email_templates/DVER_REGISTRATION_FORM.pdf"));

        File tempFile = File.createTempFile("DVER_REGISTRATION_" + dverUserVO.getUsDOT(), ".pdf");
        PdfStamper filledOutForm = new PdfStamper(reader, new FileOutputStream(tempFile));
        AcroFields form = filledOutForm.getAcroFields();
        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date date = new Date();

        form.setField("topmostSubform[0].Page1[0].notif_dt[0]", dateFormat.format(date));
        form.setField("topmostSubform[0].Page1[0].contact_nm[0]",
                dverUserVO.getFirstName() + " " + dverUserVO.getLastName());
        form.setField("topmostSubform[0].Page1[0].company[0]", dverUserVO.getCompanyName());
        form.setField("topmostSubform[0].Page1[0].address[0]",
                dverUserVO.getAddress1() + " " + dverUserVO.getAddress2());
        form.setField("topmostSubform[0].Page1[0].city[0]",
                dverUserVO.getCity() + ", " + dverUserVO.getState() + " " + dverUserVO.getZipCode());

        form.setField("topmostSubform[0].Page1[0].scac[0]", dverUserVO.getScac());
        form.setField("topmostSubform[0].Page1[0].pwd[0]", dverUserLoginVO.getPassword());

        filledOutForm.setFormFlattening(Boolean.TRUE);
        filledOutForm.close();

        DVERUtil.sendEmailWithAttachments("admin@dver.intermodal.org", "DVER Registration Confirmation",
                new InternetAddress[] { new InternetAddress(dverUserVO.getEmail()) },
                "Please see attached for your registration details.", tempFile);

        if (!dverUserVO.getEmail().equals(dverConfigVO.getEmail())) {

            PdfReader reader1 = new PdfReader(
                    servletContext.getResourceAsStream("/WEB-INF/email_templates/DVER_REGISTRATION_FORM.pdf"));
            File tempFile1 = File.createTempFile("DVER_REGISTRATION_NOTIF_" + dverUserVO.getUsDOT(), ".pdf");

            PdfStamper filledOutForm1 = new PdfStamper(reader1, new FileOutputStream(tempFile1));
            AcroFields form1 = filledOutForm1.getAcroFields();

            form1.setField("topmostSubform[0].Page1[0].notif_dt[0]", dateFormat.format(date));
            form1.setField("topmostSubform[0].Page1[0].contact_nm[0]",
                    dverConfigVO.getFirstName() + " " + dverConfigVO.getLastName());
            form1.setField("topmostSubform[0].Page1[0].company[0]", dverUserVO.getCompanyName());
            form1.setField("topmostSubform[0].Page1[0].address[0]",
                    dverUserVO.getAddress1() + " " + dverUserVO.getAddress2());
            form1.setField("topmostSubform[0].Page1[0].city[0]",
                    dverUserVO.getCity() + ", " + dverUserVO.getState() + " " + dverUserVO.getZipCode());

            form1.setField("topmostSubform[0].Page1[0].scac[0]", dverUserVO.getScac());
            form1.setField("topmostSubform[0].Page1[0].pwd[0]", dverUserLoginVO.getPassword());

            filledOutForm1.setFormFlattening(Boolean.TRUE);
            filledOutForm1.close();

            DVERUtil.sendEmailWithAttachments("admin@dver.intermodal.org", "DVER Registration Confirmation",
                    new InternetAddress[] { new InternetAddress(dverConfigVO.getEmail()) },
                    "Please see attached for your registration details.", tempFile1);
        }

        tempFile.deleteOnExit();
    } catch (Exception ex) {
        logger.error("Error in sendRegDetailEmail....." + ex);
        DVERUtil.sendExceptionEmails("sendRegDetailEmail method of RegistrationController \n " + ex);
    }
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Creates a MIME message (message with binary content carrying capabilities) from an existing Mail
 * //from   w w w .  j  a  v a  2 s.  c o m
 * @param mail The original Mail object
 * @param session Mail session
 * @return The MIME message
 */
private MimeMessage createMimeMessage(Mail mail, Session session, XWikiContext context)
        throws MessagingException, XWikiException, IOException {
    // this will also check for email error
    InternetAddress from = new InternetAddress(mail.getFrom());
    String recipients = mail.getHeader("To");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getTo();
    } else {
        recipients = mail.getTo() + "," + recipients;
    }
    InternetAddress[] to = toInternetAddresses(recipients);
    recipients = mail.getHeader("Cc");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getCc();
    } else {
        recipients = mail.getCc() + "," + recipients;
    }
    InternetAddress[] cc = toInternetAddresses(recipients);
    recipients = mail.getHeader("Bcc");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getBcc();
    } else {
        recipients = mail.getBcc() + "," + recipients;
    }
    InternetAddress[] bcc = toInternetAddresses(recipients);

    if ((to == null) && (cc == null) && (bcc == null)) {
        LOGGER.info("No recipient -> skipping this email");
        return null;
    }

    MimeMessage message = new MimeMessage(session);
    message.setSentDate(new Date());
    message.setFrom(from);

    if (to != null) {
        message.setRecipients(javax.mail.Message.RecipientType.TO, to);
    }

    if (cc != null) {
        message.setRecipients(javax.mail.Message.RecipientType.CC, cc);
    }

    if (bcc != null) {
        message.setRecipients(javax.mail.Message.RecipientType.BCC, bcc);
    }

    message.setSubject(mail.getSubject(), EMAIL_ENCODING);

    for (Map.Entry<String, String> header : mail.getHeaders().entrySet()) {
        message.setHeader(header.getKey(), header.getValue());
    }

    if (mail.getHtmlPart() != null || mail.getAttachments() != null) {
        Multipart multipart = createMimeMultipart(mail, context);
        message.setContent(multipart);
    } else {
        message.setText(mail.getTextPart());
    }

    message.setSentDate(new Date());
    message.saveChanges();
    return message;
}

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testMatchDayValidityInterval() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/*  w  ww.  j av a 2s  .  co  m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("test2@example.com"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(1, result.size());
    assertTrue(result.contains(new MailAddress("test2@example.com")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
}

From source file:edu.harvard.med.iccbl.screensaver.io.AdminEmailApplication.java

public void sendAdminEmails(String subject, String msg, Collection<ScreensaverUser> adminUsers,
        File attachedFile) throws MessagingException {
    List<String> failMessages = Lists.newArrayList();
    Set<InternetAddress> adminRecipients = Sets.newHashSet();
    adminRecipients.add(getAdminEmail());

    for (String r : getExtraRecipients()) {
        try {/*from w w  w  . j ava 2s . com*/
            adminRecipients.add(new InternetAddress(r));
        } catch (AddressException e) {
            failMessages.add("Address excption for: " + r + ", " + e.getMessage());
        }
    }

    if (adminUsers != null) {
        for (ScreensaverUser user : adminUsers) {
            String address = user.getEmail();
            if (StringUtils.isEmpty(address))
                failMessages.add("Empty address for the user: " + printUser(user));
            else {
                try {
                    adminRecipients.add(new InternetAddress(address));
                } catch (AddressException e) {
                    failMessages.add("Address excption for user: " + printUser(user) + ", " + e.getMessage());
                }
            }
        }
    }

    EmailService emailService = getEmailServiceBasedOnCommandLineOption();

    try {
        emailService.send(subject, msg.toString(), getAdminEmail(),
                adminRecipients.toArray(new InternetAddress[] {}), (InternetAddress[]) null, attachedFile);
    } catch (IOException e) {
        String errmsg = "Exception when trying to attach the file: " + attachedFile;
        log.warn(errmsg, e);
        failMessages.add(errmsg + ", " + e.getMessage());
    }

    if (!failMessages.isEmpty()) {
        sendFailMessages(subject, msg, failMessages);
    }

}

From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java

private void addReplyTo(MimeMessage mimeMessage, String replyTo) throws MessagingException {
    if (null != replyTo && replyTo.length() > 0) {
        List<Address> replyTos = new ArrayList<Address>();
        for (String part : replyTo.split("[,;\\s]")) {
            String address = part.trim();
            if (address.length() > 0) {
                replyTos.add(new InternetAddress(address));
            }/*from  www . j a v  a 2 s  . c o m*/
        }
        mimeMessage.setReplyTo(replyTos.toArray(new Address[replyTos.size()]));
    }
}

From source file:com.silverpeas.util.StringUtil.java

/**
   *//from   w  ww  .  j a  v a2  s. co m
   * Validate the form of an email address. <P> Return <tt>true</tt> only if <ul> <li>
   * <tt>aEmailAddress</tt> can successfully construct an
   * {@link javax.mail.internet.InternetAddress} <li>when parsed with "
   *
   * @" as delimiter, <tt>aEmailAddress</tt> contains two tokens which satisfy
   * {@link hirondelle.web4j.util.Util#textHasContent}. </ul> <P> The second condition arises since
   * local email addresses, simply of the form "<tt>albert</tt>", for example, are valid for
   * {@link javax.mail.internet.InternetAddress}, but almost always undesired.
   *
   * @param aEmailAddress the address to be validated
   * @return true is the address is a valid email address - false otherwise.
   */
  public static boolean isValidEmailAddress(String aEmailAddress) {
      if (aEmailAddress == null) {
          return false;
      }
      boolean result;
      try {
          new InternetAddress(aEmailAddress);
          result = Pattern.matches(EMAIL_PATTERN, aEmailAddress);
      } catch (AddressException ex) {
          result = false;
      }
      return result;
  }