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.intuit.tank.mail.TankMailer.java

/**
 * @{inheritDoc/*from  w  ww.j  ava2s. c o  m*/
 */
@Override
public void sendMail(MailMessage message, String... emailAddresses) {
    MailConfig mailConfig = new TankConfig().getMailConfig();
    Properties props = new Properties();
    props.put("mail.smtp.host", mailConfig.getSmtpHost());
    props.put("mail.smtp.port", mailConfig.getSmtpPort());

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
        fromAddress = new InternetAddress(mailConfig.getMailFrom());
        simpleMessage.setFrom(fromAddress);
        for (String email : emailAddresses) {
            try {
                toAddress = new InternetAddress(email);
                simpleMessage.addRecipient(RecipientType.TO, toAddress);
            } catch (AddressException e) {
                LOG.warn("Error with recipient " + email + ": " + e.toString());
            }
        }

        simpleMessage.setSubject(message.getSubject());
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(message.getPlainTextBody(), "text/plain");
        textPart.setHeader("MIME-Version", "1.0");
        textPart.setHeader("Content-Type", textPart.getContentType());
        // HTML version
        final MimeBodyPart htmlPart = new MimeBodyPart();
        // htmlPart.setContent(message.getHtmlBody(), "text/html");
        htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody())));
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html");
        // Create the Multipart. Add BodyParts to it.
        final Multipart mp = new MimeMultipart("alternative");
        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);
        // Set Multipart as the message's content
        simpleMessage.setContent(mp);
        simpleMessage.setHeader("MIME-Version", "1.0");
        simpleMessage.setHeader("Content-Type", mp.getContentType());
        logMsg(mailConfig.getSmtpHost(), simpleMessage);
        if (simpleMessage.getRecipients(RecipientType.TO) != null
                && simpleMessage.getRecipients(RecipientType.TO).length > 0) {
            Transport.send(simpleMessage);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.thinkbiganalytics.metadata.sla.SlaEmailService.java

/**
 * Send an email/*www. j  av a 2 s .c  o  m*/
 *
 * @param to      the user(s) to send the email to
 * @param subject the subject of the email
 * @param body    the email body
 */
public void sendMail(String to, String subject, String body) {

    try {
        if (testConnection()) {
            MimeMessage message = mailSender.createMimeMessage();
            String fromAddress = StringUtils.defaultIfBlank(emailConfiguration.getFrom(),
                    emailConfiguration.getUsername());
            message.setFrom(new InternetAddress(fromAddress));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(body);
            mailSender.send(message);
            log.debug("Email send to {}", to);
        }
    } catch (MessagingException ex) {
        log.error("Exception while sending mail : {}", ex.getMessage());
        Throwables.propagate(ex);

    }
}

From source file:models.services.Email.java

/**
 *
 * @param email/*from  w  ww  .j av  a  2s.co m*/
 * @throws AddressException
 */
public Email(String email) throws AddressException {
    super(false, KEY, false);
    if (email == null) {
        throw new IllegalArgumentException("Email address can't be null.");
    }
    this.emailAddres = new InternetAddress(email);
    emailAddres.validate();
}

From source file:com.consol.citrus.demo.devoxx.service.MailService.java

/**
 * Send mail via SMTP connection.//from w w w. j  a  v a  2  s. c om
 * @param to
 * @param subject
 * @param body
 */
public void sendMail(String to, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", mailServerHost);
    props.put("mail.smtp.port", mailServerPort);
    props.put("mail.smtp.auth", true);

    Authenticator authenticator = new Authenticator() {
        private PasswordAuthentication pa = new PasswordAuthentication(username, password);

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return pa;
        }
    };

    Session session = Session.getInstance(props, authenticator);
    session.setDebug(true);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        log.error("Failed to send mail!", e);
    }
}

From source file:fr.gael.dhus.messaging.mail.MailServer.java

public void send(Email email, String to, String cc, String bcc, String subject) throws EmailException {
    email.setHostName(getSmtpServer());/*w w  w .  j a v  a2 s. c o  m*/
    email.setSmtpPort(getPort());
    if (getUsername() != null) {
        email.setAuthentication(getUsername(), getPassword());
    }
    if (getFromMail() != null) {
        if (getFromName() != null)
            email.setFrom(getFromMail(), getFromName());
        else
            email.setFrom(getFromMail());
    }
    if (getReplyto() != null) {
        try {
            email.setReplyTo(ImmutableList.of(new InternetAddress(getReplyto())));
        } catch (AddressException e) {
            logger.error("Cannot configure Reply-to (" + getReplyto() + ") into the mail: " + e.getMessage());
        }
    }

    // Message configuration
    email.setSubject("[" + cfgManager.getNameConfiguration().getShortName() + "] " + subject);
    email.addTo(to);

    // Add CCed
    if (cc != null) {
        email.addCc(cc);
    }
    // Add BCCed
    if (bcc != null) {
        email.addBcc(bcc);
    }

    email.setStartTLSEnabled(isTls());
    try {
        email.send();
    } catch (EmailException e) {
        logger.error("Cannot send email: " + e.getMessage());
        throw e;
    }
}

From source file:edu.washington.iam.tools.IamMailSender.java

private MimeMessage genMimeMessage(IamMailMessage msg) {
    MimeMessage mime = mailSender.createMimeMessage();
    try {/*w w  w.  j  av a 2s  . c o m*/
        mime.setRecipients(RecipientType.TO, InternetAddress.parse(msg.getTo()));
        mime.setSubject(msg.makeSubstitutions(msg.getSubject()));
        mime.setReplyTo(InternetAddress.parse(replyTo));
        mime.setFrom(new InternetAddress(msg.getFrom()));
        mime.addHeader("X-Auto-Response-Suppress", "NDR, OOF, AutoReply");
        mime.addHeader("Precedence", "Special-Delivery, never-bounce");
        mime.setText(msg.makeSubstitutions(msg.getText()));
    } catch (MessagingException e) {
        log.error("iam mail build fails: " + e);
    }
    return mime;
}

From source file:au.org.ala.biocache.service.EmailService.java

/**
 * Sends an email with the supplied details. 
 * /*from   www  .  j a v a  2  s  . co  m*/
 * @param recipient
 * @param subject
 * @param content
 * @param sender
 */
public void sendEmail(String recipient, String subject, String content, String sender) {

    logger.debug("Send email to : " + recipient);
    logger.debug("Body: " + content);
    Session session = Session.getDefaultInstance(properties);

    try {

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        message.setSubject(subject);
        message.setContent(content, "text/html");
        Transport.send(message);
    } catch (Exception e) {
        logger.error("Unable to send email to " + recipient + ".\n" + content, e);
    }
}

From source file:edu.wfu.inotado.helper.NotificationHelper.java

public boolean sendEmail(User toUser, String subject, String body) {
    boolean status = false;
    InternetAddress fromAddress = null;/*from  w  ww .  ja v  a  2 s  .c  o  m*/
    String email = toUser.getEmail();

    // skip the reset if no email address found from the user
    if (StringUtils.isBlank(email)) {
        log.warn("No email address found from user " + toUser.getEid());
        return false;
    }

    try {
        String noReplyEmaillAddress = "no-reply@" + serverConfigurationService.getServerName();
        InternetAddress[] noReply = new InternetAddress[1];
        noReply[0] = new InternetAddress(noReplyEmaillAddress);

        String fromAd = serverConfigurationService
                .getString("smtpFrom@org.sakaiproject.email.api.EmailService");
        if (StringUtils.isBlank(fromAd)) {
            fromAd = noReplyEmaillAddress;
        }
        fromAddress = new InternetAddress(fromAd);
        InternetAddress[] toAddresses = new InternetAddress[1];
        toAddresses[0] = new InternetAddress(toUser.getEmail());
        List<String> headers = new ArrayList<String>();
        headers.add("Content-Type: text/html");
        emailService.sendMail(fromAddress, toAddresses, subject, body, noReply, noReply, headers);

    } catch (AddressException e) {
        log.warn("Unable to process the address ", e);
    }

    return status;
}

From source file:com.mobileman.projecth.business.MailManagerTest.java

/**
 * @throws Exception/*from   w  w w . java 2s  .c om*/
 */
@Test
public void sendMessageToAdmin_NullFrom() throws Exception {

    mailManager.sendMessageToAdmin(null, "subject1", "body");
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals(new InternetAddress("projecth@projecth.com"), messages.get(0).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("mitglied@projecth.com"),
            messages.get(0).getMimeMessage().getRecipients(Message.RecipientType.TO)[0]);
    assertEquals("subject1", messages.get(0).getMimeMessage().getSubject());
}

From source file:io.smalldata.ohmageomh.data.service.EndUserServiceImpl.java

@Override
@Transactional//from  w w w .jav  a2  s. c o  m
public void registerUser(EndUserRegistrationData registrationData) {

    if (doesUserExist(registrationData.getUsername())) {
        throw new EndUserRegistrationException(registrationData);
    }

    EndUser endUser = new EndUser();
    endUser.setUsername(registrationData.getUsername());
    endUser.setPasswordHash(passwordEncoder.encode(registrationData.getPassword()));
    endUser.setRegistrationTimestamp(OffsetDateTime.now());

    if (registrationData.getEmailAddress() != null) {
        try {
            endUser.setEmailAddress(new InternetAddress(registrationData.getEmailAddress()));
        } catch (AddressException e) {
            throw new EndUserRegistrationException(registrationData, e);
        }
    }

    endUserRepository.save(endUser);
}