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:fr.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java

public void prepare(MimeMessage message) throws Exception {

    // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369
    if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) {
        message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");
    }// w ww  .  j  a  v a  2  s.  c o  m

    if (getFrom() != null) {
        List<InternetAddress> toAddress = new ArrayList<InternetAddress>();
        toAddress.add(new InternetAddress(getFrom(), getFromName()));
        message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()]));
    }
    if (getTo() != null) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
    }
    if (getCc() != null) {
        message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc()));
    }
    if (getSubject() != null) {
        message.setSubject(getSubject());
    }

    MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
    message.setContent(mimeMultipart);

    if (getPlainTextContent() != null) {
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(getPlainTextContent(), "text/plain");
        mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(getHtmlContent(), "text/html");
        mimeMultipart.addBodyPart(htmlBodyPart);
    }

}

From source file:com.synyx.greetingcard.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from w  w w .  j a  v a 2  s .c  om
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(config.getTo(), config.getToName()));
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

From source file:domain.Employee.java

private String newPassword(String email) {

    if (email.equals("")) {
        throw new IllegalArgumentException("email must not be null");
    }/*from w  ww. j  a v a 2 s . c  om*/
    String pass = RandomStringUtils.randomAlphanumeric(8);
    //email the employee the password they can use to login

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String messagebody = String.format(
            "Dear %s %n" + "%n" + "Your account is now ready to login and submit availibility at URL %n" + "%n"
                    + "login: %s %n" + "password: %s %n" + "%n" + "Regards," + "Administration",
            getName(), getEmail(), pass);
    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("admin@poised-resource-99801.appspotmail.com", "Administration"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(getEmail(), getName()));
        msg.setSubject("Your account has been activated");
        msg.setText(messagebody);
        Transport.send(msg);
    } catch (MessagingException | UnsupportedEncodingException ex) {
        Logger.getLogger(Employee.class.getName()).log(Level.SEVERE, null, ex);
    }
    //hash the string and set the employee's password to the hashed one. USED SHA256
    System.out.println(pass);
    String hash = DigestUtils.sha256Hex(pass);
    return hash;
}

From source file:com.angstoverseer.service.mail.MailServiceImpl.java

private void sendResponseMail(final Address sender, final String answer, final String subject)
        throws Exception {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    Message mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress("overseer@thenewoverseer.appspotmail.com", "Overseer"));
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(sender.toString()));
    mimeMessage.setSubject("Re: " + subject);
    mimeMessage.setText(answer);//w  w  w .j ava2  s .  c om
    Transport.send(mimeMessage);
}

From source file:org.opentides.eventhandler.EmailHandler.java

public void sendEmail(String[] to, String[] cc, String[] bcc, String replyTo, String subject, String body,
        File[] attachments) {/*from  ww  w  .  jav  a 2  s .co m*/
    try {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setTo(toInetAddress(to));
        InternetAddress[] ccAddresses = toInetAddress(cc);
        if (ccAddresses != null)
            mimeMessageHelper.setCc(ccAddresses);
        InternetAddress[] bccAddresses = toInetAddress(bcc);
        if (bccAddresses != null)
            mimeMessageHelper.setBcc(bccAddresses);
        if (!StringUtil.isEmpty(replyTo))
            mimeMessageHelper.setReplyTo(replyTo);
        Map<String, Object> templateVariables = new HashMap<String, Object>();

        templateVariables.put("message-title", subject);
        templateVariables.put("message-body", body);

        StringWriter writer = new StringWriter();
        VelocityEngineUtils.mergeTemplate(velocityEngine, mailVmTemplate, "UTF-8", templateVariables, writer);

        mimeMessageHelper.setFrom(new InternetAddress(this.fromEmail, this.fromName));
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(writer.toString(), true);

        // check for attachment
        if (attachments != null && attachments.length > 0) {
            for (File attachment : attachments) {
                mimeMessageHelper.addAttachment(attachment.getName(), attachment);
            }
        }

        /**
         * The name of the identifier should be image
         * the number after the image name is the counter 
         * e.g. <img src="cid:image1" />
         */
        if (imagesPath != null && imagesPath.size() > 0) {
            int x = 1;
            for (String path : imagesPath) {
                FileSystemResource res = new FileSystemResource(new File(path));
                String imageName = "image" + x;
                mimeMessageHelper.addInline(imageName, res);
                x++;
            }
        }
        javaMailSender.send(mimeMessage);
    } catch (MessagingException e) {
        _log.error(e, e);
    } catch (UnsupportedEncodingException uee) {
        _log.error(uee, uee);
    }
}

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

public static synchronized InternetAddress getAuthorizedEmailAddress(String pFrom, String personalName)
        throws AddressException, UnsupportedEncodingException {
    String senderAddress = getAuthorizedEmail(pFrom);
    InternetAddress address = new InternetAddress(senderAddress, true);
    // - If email is authorized (senderAddress.equals(pFrom)), use it as it (personalName)
    // - If email is not authorized (!senderAddress.equals(pFrom)), use default one and default
    //   personal name too (notificationPersonalName)
    String personal = senderAddress.equals(pFrom) ? personalName : notificationPersonalName;
    if (StringUtil.isDefined(personal)) {
        address.setPersonal(personal, CharEncoding.UTF_8);
    }//from   ww w  .  ja v  a2  s . c  o m
    return address;
}

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

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

    PFXMailBuilder builder = new PFXMailBuilder(IOUtils.toString(new FileInputStream(templateFile)),
            templateBuilder);/*from w w  w .j a v  a 2 s .  c  o m*/

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);
    builder.addProperty("sendSMS", true);
    builder.addProperty("phoneNumberAnonymized", "1234***");
    builder.addProperty("id", "0987");

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

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

    Multipart mp;

    mp = (Multipart) message.getContent();

    BodyPart textPart = mp.getBodyPart(0);

    assertTrue(textPart.isMimeType("text/plain"));

    String body = (String) textPart.getContent();

    assertTrue(body.contains("was sent to you by SMS"));

    /*
     * 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:org.apache.archiva.redback.integration.mail.MailerImpl.java

public void sendMessage(Collection<String> recipients, String subject, String content) {
    if (recipients.isEmpty()) {
        log.warn("Mail Not Sent - No mail recipients for email. subject [{}]", subject);
        return;//from  w  w  w  . j av a  2 s .c om
    }

    String fromAddress = config.getString(UserConfigurationKeys.EMAIL_FROM_ADDRESS);
    String fromName = config.getString(UserConfigurationKeys.EMAIL_FROM_NAME);

    if (StringUtils.isEmpty(fromAddress)) {
        fromAddress = System.getProperty("user.name") + "@localhost";
    }

    // TODO: Allow for configurable message headers.

    try {

        MimeMessage message = javaMailSender.createMimeMessage();

        message.setSubject(subject);
        message.setText(content);

        InternetAddress from = new InternetAddress(fromAddress, fromName);

        message.setFrom(from);

        List<Address> tos = new ArrayList<Address>();

        for (String mailbox : recipients) {
            InternetAddress to = new InternetAddress(mailbox.trim());

            tos.add(to);
        }

        message.setRecipients(Message.RecipientType.TO, tos.toArray(new Address[tos.size()]));

        log.debug("mail content {}", content);

        javaMailSender.send(message);
    } catch (AddressException e) {
        log.error("Unable to send message, subject [{}]", subject, e);
    } catch (MessagingException e) {
        log.error("Unable to send message, subject [{}]", subject, e);
    } catch (UnsupportedEncodingException e) {
        log.error("Unable to send message, subject [{}]", subject, e);
    }
}

From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java

@Test
public void testWithAttachment() throws Exception {
    // Given:/*from   w ww.ja  v a 2 s  . c om*/
    EmailService service = makeALocalMailer();

    InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones");
    String expectedSubject = "This is a Test Email";
    String expectedTextBody = "This is a test with a PDF attachment.";
    List<FileSystemResource> filesToAttach = new ArrayList<FileSystemResource>();
    filesToAttach.add(
            new FileSystemResource(this.getClass().getClassLoader().getResource("HelloWorld.pdf").getFile()));

    // When:
    service.sendWithAttachments(expectedTo, expectedSubject, expectedTextBody, filesToAttach);

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());
    WiserMessage message = messages.get(0);
    MimeMessage mimeMessage = message.getMimeMessage();

    assertEquals("Subject;", expectedSubject, mimeMessage.getSubject());

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 2, body.getCount());

    MimeBodyPart attachment = ((MimeBodyPart) body.getBodyPart(1));
    assertTrue("Attachment MIME Type should be application/pdf", attachment.isMimeType("application/pdf"));
    assertEquals("Attachment filename;", "HelloWorld.pdf", attachment.getFileName());
    assertTrue("No content found in the attachment.", isNotBlank(attachment.getContent().toString()));
}

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

private void sendMail(LDAPUser user, boolean enabled) throws MailException {
    javax.mail.Session session = null;// ww  w .  java  2s.c o  m
    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 mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(user.getPreferredMail());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        _log.error("mail bcc: " + mailBCC);
        String ccMail[] = mailBCC.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.BCC, mailCCopy);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");
        if (enabled) {
            mailBody = mailBody.replace("_RESULT_", "accepted");
        } else {
            mailBody = mailBody.replace("_RESULT_", "denied");
        }
        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

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

}