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.ilopez.jasperemail.JasperEmail.java

public void emailReport(String emailHost, final String emailUser, final String emailPass,
        Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames,
        Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException {

    Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass
            + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport);
    Properties props = new Properties();

    // Setup Email Settings
    props.setProperty("mail.smtp.host", emailHost);
    props.setProperty("mail.smtp.port", smtpport.toString());
    props.setProperty("mail.smtp.auth", smtpauth.toString());

    if (smtpenc == OptionValues.SMTPType.SSL) {
        // SSL settings
        props.put("mail.smtp.socketFactory.port", smtpport.toString());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    } else if (smtpenc == OptionValues.SMTPType.TLS) {
        // TLS Settings
        props.put("mail.smtp.starttls.enable", "true");
    } else {//from  w  ww .j  av a2  s.  co  m
        // Plain
    }

    // Setup and Apply the Email Authentication

    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailUser, emailPass);
        }
    });

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");

    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void putMailInMailbox(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
        final MimeMessage message = new MimeMessage((Session) null);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS).getInbox().add(message);
    }/*from w w w . j a  v a  2  s .com*/

    logger.info("Putted " + messages + " into mailbox " + EMAIL_USER_ADDRESS);
}

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

protected void addRecipients(MimeMessage message, RecipientType recipientType, Collection<String> addresses)
        throws MessagingException {
    if (addresses != null && !addresses.isEmpty()) {
        Address[] addressArray = new Address[addresses.size()];
        int index = 0;
        for (String address : addresses) {
            addressArray[index++] = new InternetAddress(address);
        }// w ww . j a  va 2s .c o  m
        message.addRecipients(recipientType, addressArray);
    }
}

From source file:eu.scape_project.planning.user.Groups.java

/**
 * Sends an invitation mail to the user.
 * /*from ww w. j a v a  2 s .com*/
 * @param toUser
 *            the recipient of the mail
 * @param serverString
 *            the server string
 * @return true if the mail was sent successfully, false otherwise
 * @throws InvitationMailException
 *             if the invitation mail could not be send
 */
private void sendInvitationMail(User toUser, GroupInvitation invitation, String serverString)
        throws InvitationMailException {
    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail()));
        message.setSubject(
                user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName());

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + toUser.getFullName() + ", \n\n");
        builder.append("The Plato user " + user.getFullName() + " has invited you to join the group "
                + user.getUserGroup().getName() + ".\n");
        builder.append("Please log in and use the following link to accept the invitation: \n");
        builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid="
                + invitation.getInvitationActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Group invitation mail sent successfully to " + invitation.getEmail());

    } catch (Exception e) {
        log.error("Error sending group invitation mail to " + invitation.getEmail(), e);
        throw new InvitationMailException(e);
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraFailed(String adresaSephora, String from, String to1, String to2,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }/*  w w  w.  j  a va  2 s.com*/
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        //send message  
        Transport.send(message);

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

}

From source file:mitm.common.mail.repository.hibernate.MailRepositoryImplTest.java

@Test
public void testGetItem() throws Exception {
    MimeMessage message = loadMessage("html-alternative.eml");

    assertEquals(0, proxy.getItemCount(DEFAULT_REPOSITORY));

    MailRepositoryItem item = proxy.addItem(DEFAULT_REPOSITORY, message,
            InternetAddress.parse("test1@example.com, test2@example.com", false),
            new InternetAddress("sender@example.com"), "127.0.0.1", new Date(123456), new byte[] { 1, 2, 3 });

    MailRepositoryItem item2 = proxy.getItem(DEFAULT_REPOSITORY, item.getID());

    assertNotNull(item2);//from w  w  w  .  ja  va2 s. c o  m

    assertEquals("Open Source Group Members <group-digests@linkedin.com>", item2.getFromHeader());
    assertEquals("From Joshua Barger and other Open Source group members on LinkedIn", item2.getSubject());
    assertEquals("<1266236208.59156794.1253209950952.JavaMail.app@ech3-cdn18.prod>", item2.getMessageID());
    assertEquals("sender@example.com", item2.getSender().getAddress());
    assertEquals("127.0.0.1", item2.getRemoteAddress());
    assertEquals(123456, item2.getLastUpdated().getTime());
    assertTrue(Arrays.equals(new byte[] { 1, 2, 3 }, item2.getAdditionalData()));

    assertEquals("[test1@example.com, test2@example.com]",
            proxy.getRecipients(DEFAULT_REPOSITORY, item2.getID()).toString());

    proxy.assertMessage(DEFAULT_REPOSITORY, item2.getID(), message);
}