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, String personal) throws UnsupportedEncodingException 

Source Link

Document

Construct an InternetAddress given the address and personal name.

Usage

From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java

public void send(EmailModel model) throws EmailException {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Sending email: " + model);

    if (model == null)
        throw new NullPointerException("model");

    Properties emailProps;//from ww  w .  ja  v a2  s.  c o  m
    Session emailSession;

    // set the relay host as a property of the email session
    emailProps = new Properties();
    emailProps.setProperty("mail.transport.protocol", "smtp");
    emailProps.put("mail.smtp.host", host);
    emailProps.setProperty("mail.smtp.port", String.valueOf(port));
    // set the timeouts
    emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS));
    emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Email properties: " + emailProps);

    // set up email session
    emailSession = Session.getInstance(emailProps, null);
    emailSession.setDebug(false);

    String from;
    String displayFrom;

    String body;
    String subject;
    List<EmailAttachment> attachments;

    if (model.getFrom() == null)
        throw new NullPointerException("from");
    if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc())
            && MiscUtils.isEmpty(model.getCc()))
        throw new IllegalArgumentException("model has no addresses");

    from = model.getFrom();
    displayFrom = model.getDisplayFrom();
    body = model.getBody();
    subject = model.getSubject();
    attachments = model.getAttachments();

    MimeMessage emailMessage;
    InternetAddress emailAddressFrom;

    // create an email message from the current session
    emailMessage = new MimeMessage(emailSession);

    // set the from
    try {
        emailAddressFrom = new InternetAddress(from, displayFrom);
        emailMessage.setFrom(emailAddressFrom);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    if (!MiscUtils.isEmpty(model.getTo()))
        setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO);
    if (!MiscUtils.isEmpty(model.getCc()))
        setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC);
    if (!MiscUtils.isEmpty(model.getBcc()))
        setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC);

    try {

        if (!MiscUtils.isEmpty(subject))
            emailMessage.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (body != null) {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            String bodyContentType;
            //        body = Utils.base64Encode(body);
            bodyContentType = "text/html; charset=UTF-8";

            messageBodyPart.setContent(body, bodyContentType);
            //Content-Transfer-Encoding : base64
            //        messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
            multipart.addBodyPart(messageBodyPart);
        }
        // Part two is attachment
        if (attachments != null && !attachments.isEmpty()) {
            try {
                for (EmailAttachment a : attachments) {
                    MimeBodyPart attachBodyPart = new MimeBodyPart();
                    // don't base 64 encode
                    DataSource source = new StreamDataSource(
                            new DefaultStreamFactory(a.getInputStream(), false), a.getName(),
                            a.getContentType());
                    attachBodyPart.setDataHandler(new DataHandler(source));
                    attachBodyPart.setFileName(a.getName());
                    attachBodyPart.setHeader("Content-Type", a.getContentType());
                    attachBodyPart.addHeader("Content-Transfer-Encoding", "base64");

                    // add the attachment to the message
                    multipart.addBodyPart(attachBodyPart);

                }
            }
            // close all the input streams
            finally {
                for (EmailAttachment a : attachments)
                    MiscUtils.closeStream(a.getInputStream());
            }
        }

        // set the content
        emailMessage.setContent(multipart);
        emailMessage.saveChanges();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email message: " + emailMessage);

        Transport.send(emailMessage);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email complete.");

    } catch (Exception e) {
        throw new EmailException(e);
    }

}

From source file:mitm.application.djigzo.ca.PFXMailBuilderTest.java

@Test
public void testReplacePFX() throws Exception {
    byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX));

    PFXMailBuilder builder = new PFXMailBuilder(IOUtils.toString(new FileInputStream(templateFile)),
            templateBuilder);//from  w  w w .j  av a2  s  . c  o  m

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

    MailUtils.writeMessage(message, new File(tempDir, "testReplacePFX.eml"));

    /*
     * Check if the PFX has really been replaced
     */
    byte[] newPFX = getPFX(message);

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray());

    assertEquals(22, keyStore.size());
}

From source file:mitm.application.djigzo.james.mailets.Notify.java

private Address toAddress(String email) throws AddressException {
    Address address = null;/*w w  w  .  j  av  a2 s .c  om*/

    if (email != null) {
        address = new InternetAddress(email, false);
    }

    return address;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator.java

/**
 * Check whether the form of the emailAddress is syntactically correct. Does
 * not allow multiple addresses. Does not allow local addresses (without a
 * hostname)./*from   w ww. ja  v a  2  s .  com*/
 * 
 * Does not confirm that the host actually exists, or has a mailbox by that
 * name.
 */
public static boolean isValidEmailAddress(String emailAddress) {
    try {
        // InternetAddress constructor will throw an exception if the
        // address does not have valid format (if "strict" is true).
        @SuppressWarnings("unused")
        InternetAddress a = new InternetAddress(emailAddress, true);

        // InternetAddress permits a localname without hostname.
        // Guard against that.
        if (emailAddress.indexOf('@') == -1) {
            return false;
        }

        return true;
    } catch (AddressException e) {
        return false;
    }
}

From source file:it.infn.ct.security.utilities.LDAPCleaner.java

private void sendUserRemainder(UserRequest ur, int days) {
    javax.mail.Session session = null;//from w w  w. j  a v  a2 s  .c  o  m
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

        Message mailMsg = new MimeMessage(session);
        mailMsg.setFrom(new InternetAddress(rb.getString("mailSender"), rb.getString("IdPAdmin")));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(getGoodMail(ur),
                ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        if (rb.containsKey("mailCopy") && !rb.getString("mailCopy").isEmpty()) {

            String ccMail[] = rb.getString("mailCopy").split(";");
            InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
            for (int i = 0; i < ccMail.length; i++) {
                mailCCopy[i] = new InternetAddress(ccMail[i]);
            }

            mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy);
        }

        if (days > 0) {
            mailMsg.setSubject(
                    rb.getString("mailNotificationSubject").replace("_DAYS_", Integer.toString(days)));
            mailMsg.setText(rb.getString("mailNotificationBody")
                    .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname())
                    .replace("_DAYS_", Integer.toString(days)));
        } else {
            mailMsg.setSubject(rb.getString("mailDeleteSubject").replace("_DAYS_", Integer.toString(days)));
            mailMsg.setText(rb.getString("mailDeleteBody")
                    .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname())
                    .replace("_DAYS_", Integer.toString(days)));
        }
        Transport.send(mailMsg);

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
    }
}

From source file:com.basp.trabajo_al_minuto.model.business.BusinessUtils.java

/**
 * Se encarga de enviar el mensaje de correo electronico *
 *///w  w  w.j  a v a 2s . co m
public static Boolean sendEmail(final EmailMessage emdto) throws BusinessException {
    try {
        Session session;
        Properties properties = System.getProperties();
        properties.put("mail.host", emdto.getHost());
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.port", emdto.getPort());
        properties.put("mail.smtp.starttls.enable", emdto.getStarttls());
        if (emdto.getUser() != null && emdto.getPassword() != null) {
            properties.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(emdto.getUser(), emdto.getPassword());
                }
            });
        } else {
            properties.put("mail.smtp.auth", "false");
            session = Session.getDefaultInstance(properties);
        }

        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emdto.getFrom(), emdto.getMask()));
        message.setSubject(emdto.getSubject());

        for (String to : emdto.getToList()) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        }
        if (emdto.getCcList() != null) {
            for (String cc : emdto.getCcList()) {
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
            }
        }
        if (emdto.getCcoList() != null) {
            for (String cco : emdto.getCcoList()) {
                message.addRecipient(Message.RecipientType.BCC, new InternetAddress(cco));
            }
        }

        bodyPart = new MimeBodyPart();
        bodyPart.setContent(emdto.getBodyMessage(), emdto.getMimeTypeMessage());
        multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (emdto.getFilePaths() != null) {
            for (String filePath : emdto.getFilePaths()) {
                File file = new File(filePath);
                if (file.exists()) {
                    dataSource = new FileDataSource(file);
                    bodyPart = new MimeBodyPart();
                    bodyPart.setDataHandler(new DataHandler(dataSource));
                    bodyPart.setFileName(file.getName());
                    multipart.addBodyPart(bodyPart);
                }
            }
        }

        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException | UnsupportedEncodingException ex) {
        Logger.getLogger(BusinessUtils.class.getName()).log(Level.SEVERE, "BusinessUtils.sendEmail Exception",
                ex);
        throw new BusinessException(ex);
    }
    return Boolean.TRUE;
}

From source file:atd.backend.Register.java

public void sendRegMail(Klant k) throws IOException {
    Properties propMail = new Properties();
    InputStream config = null;/*from w w  w  .ja va  2 s . co  m*/
    config = new URL(CONFIG_URL).openStream();
    propMail.load(config);

    Properties props = new Properties();
    props.put("mail.smtp.host", propMail.getProperty("host"));
    props.put("mail.smtp.port", 465);
    props.put("mail.smtp.ssl.enable", true);
    Session mailSession = Session.getInstance(props);
    try {
        Logger.getLogger("atd.log").info("Stuurt mail naar: " + k.getEmail());
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(propMail.getProperty("email"), propMail.getProperty("mailName")));
        msg.setRecipients(Message.RecipientType.TO, k.getEmail());
        msg.setSubject("Uw account is aangemaakt");
        msg.setSentDate(Calendar.getInstance().getTime());
        msg.setContent("Beste " + k.getNaam() + ", \n\nUw account " + k.getUsername()
                + " is aangemaakt, U kunt inloggen op de <a href='https://atd.plebian.nl'>ATD website</a>\n",
                "text/html; charset=utf-8");
        // TODO: Heeft OAUTH nodig, maarja we zijn al niet erg netjes met
        // wachtwoorden
        Transport.send(msg, propMail.getProperty("email"), propMail.getProperty("password"));
    } catch (Exception e) {
        Logger.getLogger("atd.log").warning("send failed: " + e.getMessage());
    }
}

From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public void setFrom(final EmailAddress from) {
    try {/*from  w ww  . j ava2  s. co m*/
        if (from.hasName()) {
            source.setFrom(new InternetAddress(from.getEmail(), from.getName()));
        } else {
            source.setFrom(new InternetAddress(from.getEmail()));
        }
    } catch (final Exception e) {
        throw new GmailException("Failed setting from address", e);
    }
}

From source file:it.infn.ct.security.actions.RegisterUser.java

private void sendMail(UserRequest usreq) throws MailException {
    javax.mail.Session session = null;/*from  w w  w.  j  ava2 s .  c  om*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        log.error("Mail resource lookup error");
        log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, idPAdmin));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(usreq.getPreferredMail(),
                usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        String ccMail[] = mailCC.split(";");
        InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
        for (int i = 0; i < ccMail.length; i++) {
            mailCCopy[i] = new InternetAddress(ccMail[i]);
        }

        mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_",
                usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname());

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        log.error(ex);
        throw new MailException("Mail from address format not valid");
    } catch (MessagingException ex) {
        log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void passwd(Long userId, String token, String subject, String fromUser, String fromName,
        final String toUser, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link",
            MessageFormatter.arrayFormat("http://www.uengine.io/auth/passwdConfirm?userid={}&token={}",
                    new Object[] { Long.toString(userId), token }).getMessage());

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/passwd.vm", "UTF-8", model);

    try {//from w ww  .  java 2 s.  c  o  m
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}