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:Main.java

public static void main(String[] args) throws Exception {

    Properties props = new Properties();
    props.put("mail.host", "mail.cloud9.net");

    Session mailConnection = Session.getInstance(props, null);
    Message msg = new MimeMessage(mailConnection);

    Address a = new InternetAddress("a@a.com", "A a");
    Address b = new InternetAddress("fake@java2s.com");

    msg.setContent("Mail contect", "text/plain");
    msg.setFrom(a);//  w  w w  .  ja va  2s  . co  m
    msg.setRecipient(Message.RecipientType.TO, b);
    msg.setSubject("subject");

    Transport.send(msg);
}

From source file:org.trustedanalytics.user.invite.EmailService.java

public EmailService(JavaMailSender mailSender, String supportEmail, String personalName)
        throws UnsupportedEncodingException {
    if (mailSender == null) {
        throw new IllegalArgumentException("EmailService constructor contains a null JavaMailSender argument");
    }//w w w.j  a v  a2s .c o m
    if (supportEmail == null) {
        throw new IllegalArgumentException("EmailService constructor contains a null String argument");
    }
    Address[] temp = null;
    try {
        temp = new Address[] { new InternetAddress(supportEmail, personalName) };
    } catch (IllegalArgumentException e) {
        LOGGER.error(e);
    }

    this.senderAddresses = temp;
    this.mailSender = mailSender;
}

From source file:baggage.hypertoolkit.request.RequestParser.java

protected InternetAddress requiredEmail(String key, Bag<String, String> parameters)
        throws InvalidRequestException {
    validateRequiredKey(key, parameters);
    final String value = parameters.get(key);
    try {//from w  w  w  .ja  va 2 s  .c o m
        return new InternetAddress(value, true);
    } catch (AddressException e) {
        throw new InvalidRequestException("Invalid email address");
    }
}

From source file:com.miserablemind.butter.domain.service.email.EmailManager.java

/**
 * Sends e-mail address verification message to a user.
 * The method can be used for initial sign-up process as well as user e-mail address update.
 *
 * @param appUser           user instance an e-mail message is being sent to
 * @param verificationToken a token to build a verification URL that user will be identified against
 * @param configApp         app specific configuration in order to retrieve "from" value and base url
 *//*from   ww w .  ja  va  2  s . c o  m*/
@Async
public void sendEmailVerification(AppUser appUser, String verificationToken, ConfigApp configApp) {
    String subjectLine = "E-mail Verification for " + configApp.getAppName() + "!";

    try {
        InternetAddress fromField = new InternetAddress(configApp.getEmailAddressNoReply(),
                configApp.getAppName() + " - No Reply");

        EmailMessage emailMessage = new EmailMessage(appUser.getEmail(), fromField, subjectLine, null,
                "signup-confirmation.vm");
        emailMessage.addModelProperty("userName", appUser.getUsername());
        emailMessage.addModelProperty("appName", configApp.getAppName());
        emailMessage.addModelProperty("verificationUrl",
                configApp.getBaseAppUrl() + "/user/verify?token=" + verificationToken);

        this.emailService.sendMimeMail(emailMessage);
    } catch (UnsupportedEncodingException e) {
        logger.error("Could Not create InternetAddress for " + configApp.getEmailAddressNoReply(), e);
    }

}

From source file:com.hulaki.smtp.transport.SmtpMessageTest.java

@Test
public void sendEmailFrom() throws Exception {
    EmailSender emailSender = newEmailSender();
    String from = new InternetAddress(MAIL_FROM, MAIL_FROM).toString();
    String recipient = RandomData.email();
    ArgumentCaptor<SmtpMessage> messageCaptor = ArgumentCaptor.forClass(SmtpMessage.class);

    infrastructure.resetSmtpMessageObserverMock();
    emailSender.sendEmail(from, recipient, "Subject", "Body - " + RandomStringUtils.random(10));
    verify(infrastructure.getSmtpMessageObserver()).notify(messageCaptor.capture());

    assertFromHeaderEquals(messageCaptor.getValue(), from);
    assertEquals(messageCaptor.getValue().getHeaderValue("To"),
            new InternetAddress(recipient, recipient).toString());
}

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

/**
 * When we send out an email with just a text body, et expect to get a
 * Multipart email having only a plain text body.
 *///from   ww  w. j  av a 2  s.c  o m
@Test
public void testSimpleEmail() throws Exception {
    // Given:
    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 simple test.";

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

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());

    WiserMessage message = messages.get(0);
    assertNotNull("No message was actually sent.", message);
    MimeMessage mimeMessage = message.getMimeMessage();
    Address[] toRecipients = mimeMessage.getRecipients(RecipientType.TO);
    assertEquals("Number of To: Recipient;", 1, toRecipients.length);
    Address toRecipient = toRecipients[0];
    assertEquals("To: Recipient;", expectedTo, toRecipient);

    InternetAddress expectedFrom = new InternetAddress("admin@domain.com", "Domain Admin");
    Address[] fromArr = mimeMessage.getFrom();
    assertEquals("From: email addresses;", 1, fromArr.length);
    assertEquals("Email From: address,", expectedFrom, fromArr[0]);

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

    assertNotNull("The date of the email cannot be null.", mimeMessage.getSentDate());

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 1, body.getCount());
    MimeMultipart textPart = ((MimeMultipart) body.getBodyPart(0).getContent());
    assertEquals("Number of MIME parts in the text body;", 1, textPart.getCount());
    MimeBodyPart plainTextPart = ((MimeBodyPart) textPart.getBodyPart(0));
    assertTrue("Expected the plain text content to be text/plain.", plainTextPart.isMimeType("text/plain"));
    assertEquals("Text Body;", expectedTextBody, plainTextPart.getContent());
}

From source file:eu.forgestore.ws.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

    // Session session = Session.getDefaultInstance(props, null);

    props.setProperty("mail.transport.protocol", "smtp");
    if ((FStoreRepository.getPropertyByName("mailhost").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", FStoreRepository.getPropertyByName("mailhost").getValue());
    if ((FStoreRepository.getPropertyByName("mailuser").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", FStoreRepository.getPropertyByName("mailuser").getValue());
    if ((FStoreRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", FStoreRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = FStoreRepository.getPropertyByName("adminEmail").getValue();
    String subj = FStoreRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;// w ww  .j a v  a  2s. c  om
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:gr.upatras.ece.nam.baker.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

    // Session session = Session.getDefaultInstance(props, null);

    props.setProperty("mail.transport.protocol", "smtp");
    if ((BakerRepository.getPropertyByName("mailhost").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", BakerRepository.getPropertyByName("mailhost").getValue());
    if ((BakerRepository.getPropertyByName("mailuser").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", BakerRepository.getPropertyByName("mailuser").getValue());
    if ((BakerRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", BakerRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = BakerRepository.getPropertyByName("adminEmail").getValue();
    String subj = BakerRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;/*from  w ww  .  j a v a  2 s.  c o  m*/
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:nc.noumea.mairie.appock.core.utility.AppockMail.java

private InternetAddress createInternetAddress(AppUser user) throws UnsupportedEncodingException {
    if (user == null) {
        throw new IllegalArgumentException();
    }//from  ww  w .ja  va2  s .  c  o  m
    return new InternetAddress(user.getEmail(), user.getNomComplet());
}

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

public void sendMail(MessageConfig config) throws MessagingException {
    log.debug("Sending message " + config);

    Session session = getSession();/*w  w  w  . j a  va2  s .c o  m*/
    final MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        mimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(config.getTo(), config.getToName()));
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }
    mimeMessage.setSubject(config.getSubject());
    mimeMessage.setContent(config.getContent(), config.getContentType());
    // we don't send in a new Thread so that we get the Exception
    Transport.send(mimeMessage);
}