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.adobe.acs.commons.email.impl.EmailServiceImpl.java

@Override
public List<String> sendEmail(final String templatePath, final Map<String, String> emailParams,
        final String... recipients) {

    List<String> failureList = new ArrayList<String>();

    if (recipients == null || recipients.length <= 0) {
        throw new IllegalArgumentException(MSG_INVALID_RECIPIENTS);
    }/*from w  w w.  java  2 s .  c  o m*/

    List<InternetAddress> addresses = new ArrayList<InternetAddress>(recipients.length);
    for (String recipient : recipients) {
        try {
            addresses.add(new InternetAddress(recipient));
        } catch (AddressException e) {
            log.warn("Invalid email address {} passed to sendEmail(). Skipping.", recipient);
        }
    }
    InternetAddress[] iAddressRecipients = addresses.toArray(new InternetAddress[addresses.size()]);
    List<InternetAddress> failureInternetAddresses = sendEmail(templatePath, emailParams, iAddressRecipients);

    for (InternetAddress address : failureInternetAddresses) {
        failureList.add(address.toString());
    }

    return failureList;
}

From source file:Sender2.java

public void addRecipient(String message_recip) throws MessagingException {
    // TO Address
    InternetAddress toAddress = new InternetAddress(message_recip);
    mesg.addRecipient(Message.RecipientType.TO, toAddress);
}

From source file:com.adobe.acs.commons.hc.impl.SMTPMailServiceHealthCheck.java

@Override
@SuppressWarnings("squid:S1141")
public Result execute() {
    final FormattingResultLog resultLog = new FormattingResultLog();

    if (messageGatewayService == null) {
        resultLog.critical("MessageGatewayService OSGi service could not be found.");
        resultLog.info(//  w  w w  . j a va2 s.c  o m
                "Verify the Default Mail Service is active: http://<host>:<port>/system/console/components/com.day.cq.mailer.impl.CqMailingService");
    } else {
        final MessageGateway<SimpleEmail> messageGateway = messageGatewayService.getGateway(SimpleEmail.class);
        if (messageGateway == null) {
            resultLog.critical("The AEM Default Mail Service is INACTIVE, thus e-mails cannot be sent.");
            resultLog.info(
                    "Verify the Default Mail Service is active and configured: http://<host>:<port>/system/console/components/com.day.cq.mailer.DefaultMailService");
            log.warn("Could not retrieve a SimpleEmail Message Gateway");

        } else {
            try {
                List<InternetAddress> emailAddresses = new ArrayList<InternetAddress>();
                emailAddresses.add(new InternetAddress(this.toEmail));
                MailTemplate mailTemplate = new MailTemplate(IOUtils.toInputStream(MAIL_TEMPLATE),
                        CharEncoding.UTF_8);
                SimpleEmail email = mailTemplate.getEmail(StrLookup.mapLookup(Collections.emptyMap()),
                        SimpleEmail.class);

                email.setSubject("AEM E-mail Service Health Check");
                email.setTo(emailAddresses);

                email.setSocketConnectionTimeout(TIMEOUT);
                email.setSocketTimeout(TIMEOUT);
                try {
                    messageGateway.send(email);
                    resultLog.info(
                            "The E-mail Service appears to be working properly. Verify the health check e-mail was sent to [ {} ]",
                            this.toEmail);
                } catch (Exception e) {
                    resultLog.critical(
                            "Failed sending e-mail. Unable to send a test toEmail via the configured E-mail server: "
                                    + e.getMessage(),
                            e);
                    log.warn("Failed to send E-mail for E-mail Service health check", e);
                }

                logMailServiceConfig(resultLog, email);
            } catch (Exception e) {
                resultLog.healthCheckError(
                        "Sling Health check could not formulate a test toEmail: " + e.getMessage(), e);
                log.error("Unable to execute E-mail health check", e);
            }
        }
    }

    return new Result(resultLog);
}

From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java

/**
 * Convert string email addresses to proper InternetAddress
 * //w  ww .  j ava2s .  co m
 * @throws IOException
 */
private void sendMessage(String subject, String message, String from, String[] srecipients, String[] scclist,
        File attachedFile) throws MessagingException, IOException {
    InternetAddress[] recipients = new InternetAddress[srecipients.length];
    int i = 0;
    for (String r : srecipients) {
        recipients[i++] = new InternetAddress(r);

    }
    InternetAddress[] cclist = null;
    i = 0;
    if (scclist != null) {
        cclist = new InternetAddress[scclist.length];
        for (String r : scclist) {
            cclist[i++] = new InternetAddress(r);
        }
    }
    sendMessage(subject, message, new InternetAddress(from), recipients, cclist, attachedFile);
}

From source file:gov.nih.nci.cabig.caaers.tools.mail.CaaersJavaMailSender.java

@Override
public void send(MimeMessage message) {
    try {// w  w  w.j  a  va2s . c om
        String fromAddress = configuration.get(Configuration.SYSTEM_FROM_EMAIL);
        if (!fromAddress.equals(""))
            message.setFrom(new InternetAddress(fromAddress));
        super.send(message);

    } catch (MessagingException e) {
        throw new CaaersSystemException("Error while sending email", e);
    }
}

From source file:net.sf.jclal.util.mail.SenderEmail.java

/**
 * Send the email with the indicated parameters
 *
 * @param subject The subject/*from  w  ww .  ja  va 2  s .c o  m*/
 * @param content The content
 * @param reportFile The reportFile to send
 */
public void sendEmail(String subject, String content, File reportFile) {

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

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

    if (!user.isEmpty() && !pass.isEmpty()) {

        properties.setProperty("mail.user", user);

        properties.setProperty("mail.password", pass);
    }

    // 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.
        message.addRecipients(Message.RecipientType.TO, toRecipients.toString());

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

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(content);

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        if (attachReporFile) {

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile)));
            messageBodyPart.setFileName(reportFile.getName());
            multipart.addBodyPart(messageBodyPart);
        }

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);

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

    } catch (MessagingException e) {

        Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e);
    }

}

From source file:com.github.aynu.mosir.core.enterprise.mail.MailServiceImpl.java

/** {@inheritDoc} */
@Override//from ww w .j  a va  2s.c o  m
public InternetAddress createAddress(final String address) throws AddressException {
    return new InternetAddress(address);
}

From source file:org.cgiar.dapa.ccafs.tpe.service.impl.TPEMailService.java

@Override
public void contactUs(final Map<String, Object> templateVariables) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
            message.setTo(supportEmail);
            message.setFrom(new InternetAddress(adminEmail));
            message.setSubject(SUBJECT_ADMIN);
            String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "templates/contact-us.vm",
                    "UTF-8", templateVariables);
            log.info(body);//from  ww  w .j a  v a  2 s  .  c o  m
            message.setText(body, true);
        }
    };
    this.mailSender.send(preparator);

}

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 {//from  w w w. j  a  v  a  2  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;
}