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:io.kodokojo.service.SmtpEmailSender.java

public SmtpEmailSender(String host, int port, String username, String password, String fromAddr) {
    if (isBlank(host)) {
        throw new IllegalArgumentException("host must be defined.");
    }/*from w  w w .j  a va 2s . c om*/
    if (isBlank(username)) {
        throw new IllegalArgumentException("username must be defined.");
    }
    if (isBlank(password)) {
        throw new IllegalArgumentException("password must be defined.");
    }
    if (isBlank(fromAddr)) {
        throw new IllegalArgumentException("fromAddr must be defined.");
    }
    this.username = username;
    this.password = password;

    this.properties = new Properties();
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.port", Integer.toString(port));
    properties.setProperty("mail.smtp.port", Integer.toString(port));
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", true);
    properties.put("mail.smtp.starttls.required", "true");
    try {
        from = new InternetAddress(fromAddr);
    } catch (AddressException e) {
        throw new IllegalArgumentException("Unable to create an address from '" + fromAddr + "'.", e);
    }
}

From source file:com.jive.myco.seyren.core.service.notification.EmailNotificationService.java

private MimeMessage createMimeMessage(Email email) throws AddressException, MessagingException {

    MimeMessage mail = mailSender.createMimeMessage();
    InternetAddress senderAddress = new InternetAddress(email.getFrom());
    mail.addRecipient(RecipientType.TO, new InternetAddress(email.getTo()));
    mail.setSender(senderAddress);// w  w w  .  j  ava  2 s . c o  m
    mail.setFrom(senderAddress);
    mail.setText(email.getMessage());
    mail.setSubject(email.getSubject());
    mail.addHeader("Content-Type", "text/html; charset=UTF-8");

    return mail;
}

From source file:mb.MbTermin.java

private void posaljiMail(Student student, Profesor profesorId, Termin t) {

    //ToDo change username and password for google account
    final String username = "*****";
    final String password = "*****";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override/*  w  w w  . j a  v a  2  s  . c o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(profesorId.getEmail()));
        message.setSubject("Konsultacije");
        message.setText("Potovani " + profesorId.getIme() + " " + profesorId.getPrezime() + ","
                + "\n\n Student " + student.getIme() + " " + student.getPrezime()
                + " je zakazao termin konsultacija" + " za datum " + t.getTerminPK().getVreme() + ".");
        Transport.send(message);

        System.out.println("Message sent");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateAccountDeletionMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateMessage = _clazz.getDeclaredMethod("_populateMessage", String.class, String.class,
            String.class, Session.class);

    populateMessage.setAccessible(true);

    Message message = (Message) populateMessage.invoke(_classInstance, "user@test.com",
            "Account Deletion Successful", "account_deletion_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Account Deletion Successful", message.getSubject());
    Assert.assertEquals(_ACCOUNT_DELETION_EMAIL, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}

From source file:com.github.sleroy.junit.mail.server.test.MailSender.java

/**
 * Send mail./*from  ww w  .  j a va  2s.  c om*/
 *
 * @param from
 *            Sender's email ID needs to be mentioned
 * @param to
 *            Recipient's email ID needs to be mentioned.
 * @param subject
 *            the subject
 * @throws MessagingException
 */
public void sendMail(String from, String to, String subject, String body) throws MessagingException {

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.port", Integer.toString(port));

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    Transport transport = null;
    try {
        transport = session.getTransport();

        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Set Subject: header field
        message.setSubject(subject);

        // Now set the actual message
        message.setText(body);

        // Send message
        transport.send(message);
        System.out.println("Sent message successfully....");
    } finally {
        if (transport != null) {
            transport.close();
        }
    }

}

From source file:EmailJndiServlet.java

private void sendMessage(String to, String from, String subject, String bodyContent) throws Exception {

    Message mailMsg = null;//ww w  .  jav  a2 s .com

    synchronized (mailSession) {

        mailMsg = new MimeMessage(mailSession);//a new email message
    }

    InternetAddress[] addresses = null;

    try {

        if (to != null) {

            //throws 'AddressException' if the 'to' email address
            //violates RFC822 syntax
            addresses = InternetAddress.parse(to, false);

            mailMsg.setRecipients(Message.RecipientType.TO, addresses);

        } else {

            throw new MessagingException("The mail message requires a 'To' address.");

        }

        if (from != null)
            mailMsg.setFrom(new InternetAddress(from));

        if (subject != null)
            mailMsg.setSubject(subject);

        if (bodyContent != null)
            mailMsg.setText(bodyContent);

        //Finally, send the mail message; throws a 'SendFailedException' 
        //if any of the message's recipients have an invalid adress
        Transport.send(mailMsg);

    } catch (Exception exc) {

        throw exc;
    }
}

From source file:com.warsaw.data.controller.LoginController.java

private Message buildEmail(Session session, String to) throws Exception {
    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(EMAIL));

    // Set To: header field of the header.
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

    // Set Subject: header field
    message.setSubject("Testing Subject");

    // This mail has 2 part, the BODY and the embedded image
    MimeMultipart multipart = new MimeMultipart("related");

    // first part (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<img style='width:800px' src=\"cid:image1\"><br/>" + "Dzie dobry,<br/><br/>"
            + "witamy na portalu TrasyPoWarszawsku.pl, na ktrym zostalo "
            + "zaoone konto<br/> dla osoby o danych: Jan Marian Ptak. W celu zakoczenia procesu tworzenia "
            + "konta prosimy uy linku aktywacyjnego:<br/><br/>"
            + "<a href='https://test.puesc.gov.pl?link=Gkhh&%JK.'>https://test.puesc.gov.pl?link=Gkhh&%JK.</a><br/><br/>"
            + "Na wywietlonym ekranie prosz wprowadzi zdefiniowane przez siebie haso awaryjne. Po prawidowym"
            + " wprowadzeniu danych<br/> oraz  ustawieniu nowego  hasa dostpowego  konto  na portalu PUESC zostanie aktywowane.<br/>"
            + "Link aktywacyjny pozostanie wany przez 24 godziny od momentu  otrzymania niniejszej wiadomoci.<br/><br/>"
            + "<img style='width:800px' src=\"cid:image2\"><br/><br/>" + "Z powaaniem<br/><br/>"
            + "Zesp portalu PUESC<br/>" + "puesc@mofnet.gov.pl<br/>"
            + "<a href='http://puesc.gov.pl'>http://puesc.gov.pl</a>";

    messageBodyPart.setContent(htmlText, "text/html; charset=ISO-8859-2");
    // add it//  ww  w  .j  a  v a2s  .c o m
    multipart.addBodyPart(messageBodyPart);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("C:\\Users\\Pawel\\Desktop\\header.png");

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image1>");

    // add image to the multipart
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    //  URL url = new URL("http://ns3342351.ovh.net:8080/seap_lf_graphicsLayout_theme/images/refresh.png");
    // URLDataSource fds1 =new URLDataSource(url);
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image2>");
    multipart.addBodyPart(messageBodyPart);

    // put everything together
    message.setContent(multipart);

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    try {
        message.writeTo(b);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return message;
}

From source file:com.jwm123.loggly.reporter.ReportMailer.java

public void send() throws MessagingException {
    if (StringUtils.isNotBlank(config.getMailServer()) && recipients.length > 0) {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.port", config.getMailPort().toString());
        props.setProperty("mail.smtp.host", config.getMailServer());
        if (StringUtils.isNotBlank(config.getMailUsername())
                && StringUtils.isNotBlank(config.getMailPassword())) {
            props.setProperty("mail.smtp.user", config.getMailUsername());
            props.setProperty("mail.smtp.password", config.getMailPassword());
        }/*from ww w . java2 s .  c om*/

        Session session = Session.getDefaultInstance(props);

        MimeMessage message = new MimeMessage(session);
        message.addFrom(new Address[] { new InternetAddress(config.getMailFrom()) });
        message.setSubject(subject);
        for (String recipient : recipients) {
            message.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        MimeMultipart containingMultipart = new MimeMultipart("mixed");

        MimeMultipart messageMultipart = new MimeMultipart("alternative");
        containingMultipart.addBodyPart(newMultipartBodyPart(messageMultipart));

        messageMultipart.addBodyPart(newTextBodyPart(getText()));

        MimeMultipart htmlMultipart = new MimeMultipart("related");
        htmlMultipart.addBodyPart(newHtmlBodyPart(getHtml()));
        messageMultipart.addBodyPart(newMultipartBodyPart(htmlMultipart));

        containingMultipart.addBodyPart(addReportAttachment());

        message.setContent(containingMultipart);

        Transport.send(message);
    }
}

From source file:com.commoncoupon.mail.EmailProcessor.java

public Integer call() throws Exception {
    MimeMessage message = new MimeMessage(getSession());

    try {/*from www . j a  v  a2  s .  c o m*/
        if (from != null && (from != null && from.trim() != "")) {
            InternetAddress sentFrom = new InternetAddress(from);
            message.setFrom(sentFrom);
            if (log.isDebugEnabled())
                log.debug("Email sent from: " + sentFrom);
        }

        if (to != null && to.length > 0) {
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                sendTo[i] = new InternetAddress((String) to[i]);
                if (log.isDebugEnabled())
                    log.debug("Sending e-mail to: " + to[i]);
            }
            message.setRecipients(Message.RecipientType.TO, sendTo);
        }

        if (cc != null && cc.length > 0) {
            InternetAddress[] copyTo = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                copyTo[i] = new InternetAddress((String) cc[i]);
                if (log.isDebugEnabled())
                    log.debug("Copying e-mail to: " + cc[i]);
            }
            message.setRecipients(Message.RecipientType.CC, copyTo);
        }
        message.setSentDate(new Date());
        message.setSubject(subject);
        message.setContent(content, mimeType);
        Transport.send(message);
    } catch (Exception e) {
        log.error("Failed to send email.", e);
        return (1);
    }

    return (0);
}

From source file:org.lf.yydp.service.film.BuyTicketService.java

/**
 * :?/*from   w w  w.  j ava 2s . c  om*/
 * @param receiver
 */
public void sendEmail(String receiver) {
    Properties p = null;
    InputStream inputSteam = null;
    String senter = null;
    String Subject = null;
    String Content = null;
    try {
        p = new Properties();
        inputSteam = BuyTicketService.class.getClassLoader().getResourceAsStream("mail.properties");
        p.load(inputSteam);
        final String uname = p.getProperty("mail.uname");
        final String license = p.getProperty("mail.license");
        senter = p.getProperty("mail.senter");
        Subject = p.getProperty("mail.subject");
        Content = p.getProperty("mail.content");
        Authenticator authenticator = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uname, license);
            }
        };
        Session session = Session.getInstance(p, authenticator);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(senter));
        msg.setRecipient(RecipientType.TO, new InternetAddress(receiver));
        msg.setSubject(Subject);
        msg.setContent(Content, "text/html;charset=utf-8");
        Transport.send(msg);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (inputSteam != null) {
                inputSteam.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }
}