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:edu.harvard.med.iccbl.screensaver.io.AdminEmailApplication.java

/**
 * Send email to the administratorUser (running this program), to the "extra recipients" (specified on the
 * command line), and to the admin accounts, passed in.
 * //  w  w w .  j av a2  s  .  co m
 * @param subject
 * @param msg
 * @throws MessagingException
 */
public boolean sendEmails(String subject, String msg, Collection<? extends ScreensaverUser> users)
        throws MessagingException {
    List<String> failMessages = Lists.newArrayList();
    Set<InternetAddress> recipients = Sets.newHashSet();

    if (users != null) {
        for (ScreensaverUser user : users) {
            String address = user.getEmail();
            if (StringUtils.isEmpty(address))
                failMessages.add("Empty address for the user: " + printUser(user));
            else {
                try {
                    recipients.add(new InternetAddress(address));
                } catch (AddressException e) {
                    failMessages.add("Address excption for user: " + printUser(user) + ", " + e.getMessage());
                }
            }
        }
    }

    if (!recipients.isEmpty()) {
        EmailService emailService = getEmailServiceBasedOnCommandLineOption();

        emailService.send(subject, msg.toString(), getAdminEmail(),
                recipients.toArray(new InternetAddress[] {}), (InternetAddress[]) null);
    }
    if (!failMessages.isEmpty()) {
        sendFailMessages(subject, msg, failMessages);
    }
    return failMessages.isEmpty();
}

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

@Test
public void testProcessEmailSimpleText() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);

    MessageListener mockListener2 = mock(MessageListener.class);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Simple text Email test");
    mail.setText(textEmailContent);//from  w w w  .  ja  v  a 2 s .com
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Simple text Email test", message.getTitle());
    assertEquals(textEmailContent, message.getBody());
    assertEquals(textEmailContent.substring(0, 200), message.getSummary());
    assertEquals(0, message.getAttachmentsSize());
    assertEquals(0, message.getAttachments().size());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/plain; charset=" + System.getProperty("file.encoding"), message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

/**
 * @return l'adresse mail du testeur (en mode non production), null si la personne connecte n'a pas d'email renseign ou s'il n'y a personne de connect
 * (ex : cas d'un job quartz)/*ww  w  .j av a 2s.c  o  m*/
 * @throws AddressException
 */
private InternetAddress getAdresseMailDestinataireTesteur() throws AddressException {
    AppUser currentUser = authHelper.getCurrentUser();
    if (currentUser == null) {
        return null; // pas de personne connecte => pas de destinataire testeur
    }
    String email = currentUser.getEmail();
    return StringUtils.isNotBlank(email) ? new InternetAddress(email) : null;
}

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

@Override
protected Address getReplyTo(Mail mail) throws MessagingException {
    return replyTo != null ? new InternetAddress(replyTo) : null;
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

public AmazonAwsIamAccountCreator(Environment environment) {
    this.environment = Preconditions.checkNotNull(environment);
    try {/*ww  w. j av  a  2s.c  o  m*/
        keyPairGenerator = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER_NAME);
        keyPairGenerator.initialize(1024, new SecureRandom());

        String credentialsFileName = "AwsCredentials-" + environment.getIdentifier() + ".properties";
        InputStream credentialsAsStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(credentialsFileName);
        Preconditions.checkNotNull(credentialsAsStream,
                "File '/" + credentialsFileName + "' NOT found in the classpath");
        AWSCredentials awsCredentials = new PropertiesCredentials(credentialsAsStream);
        iam = new AmazonIdentityManagementClient(awsCredentials);

        ses = new AmazonSimpleEmailServiceClient(awsCredentials);

        ec2 = new AmazonEC2Client(awsCredentials);
        ec2.setEndpoint("ec2.eu-west-1.amazonaws.com");

        InputStream smtpPropertiesAsStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("smtp.properties");
        Preconditions.checkNotNull(smtpPropertiesAsStream,
                "File '/smtp.properties' NOT found in the classpath");

        final Properties smtpProperties = new Properties();
        smtpProperties.load(smtpPropertiesAsStream);

        mailSession = Session.getInstance(smtpProperties, null);
        mailTransport = mailSession.getTransport();
        if (smtpProperties.containsKey("mail.username")) {
            mailTransport.connect(smtpProperties.getProperty("mail.username"),
                    smtpProperties.getProperty("mail.password"));
        } else {
            mailTransport.connect();
        }
        try {
            mailFrom = new InternetAddress(smtpProperties.getProperty("mail.from"));
        } catch (Exception e) {
            throw new MessagingException("Exception parsing 'mail.from' from 'smtp.properties'", e);
        }

    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

private InternetAddress defaultFrom() throws AddressException {
    return new InternetAddress(configService.getDefaultFromEmailAddress());
}

From source file:net.sf.yal10n.DetectChangesMojo.java

void createAndSendEmail(DashboardConfiguration config, Repository repo, String projectName, String viewvcDiff,
        UnifiedDiff unifiedDiff) {// w  ww  . j av  a  2s .  com
    Properties props = new Properties();
    props.put("mail.smtp.host", config.getNotification().getSmtpServer());
    props.put("mail.smtp.port", config.getNotification().getSmtpPort());

    InternetAddress from;
    try {
        from = new InternetAddress(config.getNotification().getMailFrom());
        List<Address> recipients = config.getNotification().getRecipientsAddresses();
        recipients.addAll(repo.getNotification().getRecipientsAddresses());
        String subject = config.getNotification().getSubject().replaceAll(Pattern.quote("{{projectName}}"),
                projectName);
        String content = "<html><body>Changes detected in <strong>" + projectName + "</strong><br>"
                + "<p>See here: <a href=\"" + viewvcDiff + "\">" + viewvcDiff + "</a></p>" + "<br>"
                + "<strong>Diff output:</strong><br>" + unifiedDiff.asHtmlSnippet() + "</body></html>";

        emailer.sendEmail(skipEmail, props, from, recipients, subject, content, projectName);
    } catch (AddressException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.adobe.acs.commons.email.impl.EmailServiceImpl.java

@Override
public List<String> sendEmail(String templatePath, Map<String, String> emailParams,
        Map<String, DataSource> attachments, String... recipients) {
    List<String> failureList = new ArrayList<String>();

    if (recipients == null || recipients.length <= 0) {
        throw new IllegalArgumentException(MSG_INVALID_RECIPIENTS);
    }/*from ww w .j  a v a  2s .  com*/

    List<InternetAddress> addresses = new ArrayList<InternetAddress>(recipients.length);
    for (String recipient : recipients) {
        try {
            addresses.add(new InternetAddress(recipient));
        } catch (AddressException e) {
            log.warn("Invalid email address {} passed to sendEmail(). Skipping.", recipient);
        }
    }
    InternetAddress[] iAddressRecipients = addresses.toArray(new InternetAddress[addresses.size()]);
    List<InternetAddress> failureInternetAddresses = sendEmail(templatePath, emailParams, attachments,
            iAddressRecipients);

    for (InternetAddress address : failureInternetAddresses) {
        failureList.add(address.toString());
    }

    return failureList;
}

From source file:de.betterform.connector.smtp.SMTPSubmissionHandler.java

private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception {
    URL url = new URL(uri);
    String recipient = url.getPath();

    String server = null;/*from   w  w  w  .j  a  va 2 s.c  om*/
    String port = null;
    String sender = null;
    String subject = null;
    String username = null;
    String password = null;

    StringTokenizer headers = new StringTokenizer(url.getQuery(), "&");

    while (headers.hasMoreTokens()) {
        String token = headers.nextToken();

        if (token.startsWith("server=")) {
            server = URLDecoder.decode(token.substring("server=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("port=")) {
            port = URLDecoder.decode(token.substring("port=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("sender=")) {
            sender = URLDecoder.decode(token.substring("sender=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("subject=")) {
            subject = URLDecoder.decode(token.substring("subject=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("username=")) {
            username = URLDecoder.decode(token.substring("username=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("password=")) {
            password = URLDecoder.decode(token.substring("password=".length()), "UTF-8");

            continue;
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("smtp server '" + server + "'");

        if (username != null) {
            LOGGER.debug("smtp-auth username '" + username + "'");
        }

        LOGGER.debug("mail sender '" + sender + "'");
        LOGGER.debug("subject line '" + subject + "'");
    }

    Properties properties = System.getProperties();
    properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled()));
    properties.put("mail.smtp.from", sender);
    properties.put("mail.smtp.host", server);

    if (port != null) {
        properties.put("mail.smtp.port", port);
    }

    if (username != null) {
        properties.put("mail.smtp.auth", String.valueOf(true));
        properties.put("mail.smtp.user", username);
    }

    Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password));

    MimeMessage message = null;
    if (mediatype.startsWith("multipart/")) {
        message = new MimeMessage(session, new ByteArrayInputStream(data));
    } else {
        message = new MimeMessage(session);
        if (mediatype.toLowerCase().indexOf("charset=") == -1) {
            mediatype += "; charset=\"" + encoding + "\"";
        }
        message.setText(new String(data, encoding), encoding);
        message.setHeader("Content-Type", mediatype);
    }

    message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
    message.setSubject(subject);
    message.setSentDate(new Date());

    Transport.send(message);
}