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

public void setFrom(String sender) throws MessagingException {
    // From Address - this should come from a Properties...
    mesg.setFrom(new InternetAddress(sender));
}

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

@Test
public void mailAddressHandlerRetry() throws Exception {
    final int retries = 4;

    final MutableInt count = new MutableInt();

    MailAddressHandler.HandleUserEventHandler eventHandler = new MailAddressHandler.HandleUserEventHandler() {
        @Override/*from   w  w  w  .j a v  a  2 s .c  o  m*/
        public void handleUser(User user) throws MessagingException {
            count.increment();

            throw new ConstraintViolationException("Dummy ConstraintViolationException", null, "");
        }
    };

    MailAddressHandler handler = new MailAddressHandler(sessionManager, userWorkflow, actionExecutor,
            eventHandler, retries);

    Collection<MailAddress> recipients = MailAddressUtils
            .fromAddressArrayToMailAddressList(new InternetAddress("test@example.com"));

    try {
        handler.handleMailAddresses(recipients);

        fail();
    } catch (MessagingException e) {
        assertTrue(ExceptionUtils.getRootCause(e) instanceof ConstraintViolationException);
    }

    assertEquals(5, count.intValue());
}

From source file:com.adaptris.mail.MailSenderImp.java

@Override
public void setFrom(String from) throws MailException {
    try {/* w  w  w .j av  a 2s.co  m*/
        setFrom(new InternetAddress(from));
    } catch (AddressException e) {
        throw new MailException(e);
    }
}

From source file:com.github.thorqin.toolkit.mail.MailService.java

private void sendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    final Session session;
    props.put("mail.smtp.auth", String.valueOf(setting.auth));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", setting.host);
    props.put("mail.smtp.port", setting.port);
    if (setting.secure.equals(SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");

    } else if (setting.secure.equals(SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", setting.port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
    }// ww  w  .  j  a  v a 2s.  co  m
    if (!setting.auth)
        session = Session.getInstance(props);
    else
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(setting.user, setting.password);
            }
        });

    if (setting.debug)
        session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (setting.from != null)
            message.setFrom(new InternetAddress(setting.from));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (setting.trace && tracer != null) {
            Tracer.Info info = new Tracer.Info();
            info.catalog = "mail";
            info.name = "send";
            info.put("sender", StringUtils.join(message.getFrom()));
            info.put("recipients", mail.to);
            info.put("SMTPServer", setting.host);
            info.put("SMTPAccount", setting.user);
            info.put("subject", mail.subject);
            info.put("startTime", beginTime);
            info.put("runningTime", System.currentTimeMillis() - beginTime);
            tracer.trace(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:com.email.SendEmailCalInvite.java

/**
 * Builds the calendar invite for the email
 *
 * @param eml EmailOutInvitesModel/*from www  .j  av a 2 s. c o  m*/
 * @return BodyPart (calendar invite)
 */
private static BodyPart inviteCalObject(EmailOutInvitesModel eml, SystemEmailModel account,
        String emailSubject) {
    BodyPart calendarPart = new MimeBodyPart();
    try {
        String calendarContent = "BEGIN:VCALENDAR\n" + "METHOD:REQUEST\n" + "PRODID: BCP - Meeting\n"
                + "VERSION:2.0\n" + "BEGIN:VEVENT\n" + "DTSTAMP:"
                + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + "\n" + "DTSTART:"
                + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + "\n" + "DTEND:"
                + Global.getiCalendarDateFormat().format(eml.getHearingEndTime()) + "\n"
                //Subject
                + "SUMMARY:" + emailSubject.replace("Upcoming", "").trim() + "\n" + "UID:"
                + Calendar.getInstance().get(Calendar.MILLISECOND) + "\n"
                //return email
                + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:"
                + new InternetAddress(account.getEmailAddress()).getAddress() + "\n"
                //return email
                + "ORGANIZER:MAILTO:" + new InternetAddress(account.getEmailAddress()).getAddress() + "\n"
                //hearing room
                + "LOCATION: " + eml.getHearingRoomAbv() + "\n"
                //subject
                + "DESCRIPTION: " + emailSubject + "\n" + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n"
                + "STATUS:CONFIRMED\n" + "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n" + "ACTION:DISPLAY\n"
                + "DESCRIPTION:REMINDER\n" + "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n"
                + "END:VEVENT\n" + "END:VCALENDAR";
        calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage");
        calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL");
    } catch (MessagingException ex) {
        ExceptionHandler.Handle(ex);
    }
    return calendarPart;
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testGetAllRecipients() throws AddressException, MessagingException {
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    mail.addFrom(new InternetAddress[] { new InternetAddress("bart.simpson@silverpeas.com") });
    mail.addRecipient(RecipientType.TO, new InternetAddress("lisa.simpson@silverpeas.com"));
    mail.addRecipient(RecipientType.TO, new InternetAddress("marge.simpson@silverpeas.com"));
    mail.addRecipient(RecipientType.CC, new InternetAddress("homer.simpson@silverpeas.com"));
    mail.addRecipient(RecipientType.CC, new InternetAddress("krusty.theklown@silverpeas.com"));
    mail.addRecipient(RecipientType.BCC, new InternetAddress("ned.flanders@silverpeas.com"));
    mail.addRecipient(RecipientType.BCC, new InternetAddress("ted.flanders@silverpeas.com"));
    Set<String> recipients = messageChecker.getAllRecipients(mail);
    assertNotNull(recipients);/*  w  w w.  j a va  2s . c  om*/
    assertEquals(6, recipients.size());
    assertTrue(recipients.contains("lisa.simpson@silverpeas.com"));
    assertTrue(recipients.contains("marge.simpson@silverpeas.com"));
    assertTrue(recipients.contains("homer.simpson@silverpeas.com"));
    assertTrue(recipients.contains("krusty.theklown@silverpeas.com"));
    assertTrue(recipients.contains("ned.flanders@silverpeas.com"));
    assertTrue(recipients.contains("ted.flanders@silverpeas.com"));
}

From source file:mitm.application.djigzo.james.matchers.MailAddressMatcherTest.java

@Test
public void mailAddressMatcherRetrySuccess() throws Exception {
    final int retries = 4;

    final MutableInt count = new MutableInt();

    MailAddressMatcher.HasMatchEventHandler handler = new MailAddressMatcher.HasMatchEventHandler() {
        @Override//from ww w .j  av a2 s . co  m
        public boolean hasMatch(User user) throws MessagingException {
            count.increment();

            if (count.intValue() <= retries) {
                throw new ConstraintViolationException("Dummy ConstraintViolationException", null, "");
            }

            return true;
        }
    };

    MailAddressMatcher matcher = new MailAddressMatcher(sessionManager, userWorkflow, actionExecutor, handler,
            retries);

    Collection<MailAddress> recipients = MailAddressUtils
            .fromAddressArrayToMailAddressList(new InternetAddress("test@example.com"));

    Collection<MailAddress> result = matcher.getMatchingMailAddresses(recipients);

    assertEquals(retries + 1, count.intValue());
    assertEquals(1, result.size());
    assertEquals("test@example.com", result.iterator().next().toString());
}

From source file:AmazonSESSample.java

private static RawMessage getRawMessage() throws MessagingException, IOException {
    // JavaMail representation of the message
    Session s = Session.getInstance(new Properties(), null);
    s.setDebug(true);//from   ww  w.  ja v a 2 s .c o  m
    MimeMessage msg = new MimeMessage(s);

    // Sender and recipient
    msg.setFrom(new InternetAddress("aravind@gofastpay.com"));
    InternetAddress[] address = { new InternetAddress("aravind@gofastpay.com") };
    msg.setRecipients(javax.mail.Message.RecipientType.TO, address);
    msg.setSentDate(new Date());
    // Subject
    msg.setSubject(SUBJECT);

    // Add a MIME part to the message
    //MimeMultipart mp = new MimeMultipart();
    Multipart mp = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    //mimeBodyPart.setText(BODY);

    //BodyPart part = new MimeBodyPart();
    //String myText = BODY;
    //part.setContent(URLEncoder.encode(myText, "US-ASCII"), "text/html");
    //part.setText(BODY);
    //mp.addBodyPart(part);
    //msg.setContent(mp);
    mimeBodyPart.setContent(BODY, "text/html");
    mp.addBodyPart(mimeBodyPart);
    msg.setContent(mp);

    // Print the raw email content on the console
    //PrintStream out = System.out;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.writeTo(out);
    //String rawString = out.toString();
    //byte[] bytes = IOUtils.toByteArray(msg.getInputStream());
    //ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
    //ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.getEncoder().encode(rawString.getBytes()));

    //byteBuffer.put(bytes);
    //byteBuffer.put(Base64.getEncoder().encode(bytes));
    RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(out.toByteArray()));
    return rawMessage;
}

From source file:com.bia.monitor.service.EmailService.java

/**
 *
 * @param recipients/*  w  ww  . j a  v a2  s .c  o  m*/
 * @param subject
 * @param message
 * @param from
 * @throws MessagingException
 */
private void sendSSMessage(String recipients[], String subject, String message) {

    try {

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            if (recipients[i] != null && recipients[i].length() > 0) {
                addressTo[i] = new InternetAddress(recipients[i]);
            }
        }
        send(addressTo, subject, message);

    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        //throw new RuntimeException("Error sending email, please check to and from emails are correct!");
    }
}

From source file:com.berwickheights.spring.svc.SendEmailSvcImpl.java

/**
 * Sets the "from" part of the email//w ww . ja va 2  s  .  c  om
 */
public void setFrom(String from) {
    try {
        this.from = new InternetAddress(from);
    } catch (AddressException e) {
        throw new IllegalArgumentException("The given From address (" + from + " is not valid");
    }
}