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:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public MimeMessageHelper addTo(String to) throws AddressException, MessagingException {
    for (String recipient : to.split(";")) {
        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
    }//from   w  ww . jav  a  2  s. co  m
    return this;
}

From source file:com.netspective.commons.message.SendMail.java

protected Address[] getAddresses(Value value) throws AddressException, MessagingException {
    if (value.isListValue()) {
        String[] addressTexts = value.getTextValues();
        Address[] result = new Address[addressTexts.length];
        for (int i = 0; i < addressTexts.length; i++)
            result[i] = new InternetAddress(addressTexts[i]);
        return result;
    } else//ww  w .  j a  v a2s. c  om
        return InternetAddress.parse(value.getTextValue());
}

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

@Test
public void testPopulatePaymentFailedMessage() 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", "Payment Failed",
            "payment_failed_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Payment Failed", message.getSubject());
    Assert.assertEquals(_PAYMENT_FAILED_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.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message/*w ww .  j a v  a2s .co m*/
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

From source file:com.silverpeas.mailinglist.service.notification.AdvancedNotificationHelperTest.java

@Test
public void testMultiSendMail() throws Exception {
    MimeMessage mail = new MimeMessage(notificationHelper.getSession());
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { theSimpsons });
    mail.setSubject("Simple text Email test");
    mail.setText(textEmailContent);//from   w w  w.  j  a  v  a  2s .  c  o  m
    List<ExternalUser> externalUsers = new LinkedList<ExternalUser>();
    ExternalUser user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("bart.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("homer.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("lisa.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("marge.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("maggie.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("ned.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("maude.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("rod.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("todd.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("krusty.theklown@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("selma.bouvier@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("patty.bouvier@silverpeas.com");
    externalUsers.add(user);
    assertThat(externalUsers.size(), is(12));
    notificationHelper.sendMail(mail, externalUsers);
    Iterator<ExternalUser> iter = externalUsers.iterator();
    while (iter.hasNext()) {
        ExternalUser recipient = iter.next();
        checkSimpleEmail(recipient.getEmail(), "Simple text Email test");
    }
}

From source file:app.logica.gestores.GestorEmail.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to/*from w  ww.ja  v  a  2 s .  c  o m*/
 *            Email address of the receiver.
 * @param from
 *            Email address of the sender, the mailbox account.
 * @param subject
 *            Subject of the email.
 * @param bodyText
 *            Body text of the email.
 * @param file
 *            Path to the file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
private MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        File file) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(file);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(file.getName());

    multipart.addBodyPart(mimeBodyPart);
    email.setContent(multipart);

    return email;
}

From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

@Override
public void sendSimpleMail(String[] address, String from, String title, String content) {
    LOG.debug("sendEmail() to: " + Arrays.toString(address));
    if (address == null || address.length == 0) {
        LOG.error("the address is empty!");
        return;/*w w w  . j  av a2 s  .c  om*/
    }
    try {
        Address[] addressArray = new Address[address.length];
        int index = 0;
        for (String str : address) {
            addressArray[index++] = new InternetAddress(str);
        }
        MimeMessage msg = getMessage(addressArray, from, content, title);
        if (m_bag.m_fromAddress != null && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) {
            cheat(msg,
                    m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@")));
        }
        Transport.send(msg);
        LOG.info("Successfully send the mail to " + Arrays.toString(address));

    } catch (MessagingException e) {
        LOG.error("Exception occured while trying to send notification to: " + Arrays.toString(address), e);
        LOG.debug("Details:", e);
    }
}

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

@Test
public void testRequestCertificateOverrideCertificateRequestHandler() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    // specify an unknown request handler so we can check the queue
    mailetConfig.setInitParameter("certificateRequestHandler", "unknown");

    mailet.init(mailetConfig);/*w w w.  jav a2s  . c o m*/

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("from@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("to@example.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("somethingelse@example.com"));

    mailet.service(mail);

    assertEquals(0, proxy.getCertificateRequestStoreSize());
    assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize());
}

From source file:net.fenyo.mail4hotspot.service.AdvancedServicesImpl.java

@Scheduled(fixedDelay = 5000)
public void sendNewMails() {
    try {/*from w  w w . j  av a2 s. c  om*/
        synchronized (new_mails_working_sync) {
            if (new_mails_working == true)
                return;
            new_mails_working = true;
        }

        final List<AccountAndOutboxMail> accounts_and_mails = generalServices.getSentMails();

        for (AccountAndOutboxMail account_and_mail : accounts_and_mails) {
            boolean should_remove_user_id_processing = false;
            final User user = generalServices.getUserByAccount(account_and_mail.account);

            try {
                boolean abort_this_try = false;

                synchronized (userIdsProcessing) {
                    if (userIdsProcessing.contains(user.getId())) {
                        log.warn("account is currently processed");
                        abort_this_try = true;
                    } else {
                        should_remove_user_id_processing = true;
                        userIdsProcessing.add(user.getId());
                    }
                }

                final MailManager manager = new MailManager();
                if (abort_this_try == false) {
                    try {
                        manager.connectToRelay(account_and_mail.account.getProvider(),
                                account_and_mail.account.getUsername(), account_and_mail.account.getPassword());
                    } catch (final MessagingException ex) {
                        // le mieux serait de ne pas supprimer dans tous les cas, mais de compter le nombre de tentative et de les espacer
                        log.warn("can not connect to Relay: " + ex.toString());
                        abort_this_try = true;
                        generalServices.removeSentMail(account_and_mail.mail);
                        generalServices.sendInternalMailByAccount(account_and_mail.account,
                                "It was not possible to send your mail",
                                "An exception occured while sending your mail:\n" + ex.toString()
                                        + "\n\nthis mail has not been sent:\n-----\n" + "From: "
                                        + account_and_mail.account.getEmail() + "\n" + "To: "
                                        + account_and_mail.mail.getToAddr() + "\n" + "Cc: "
                                        + ((account_and_mail.mail.getCcAddr() == null) ? ""
                                                : account_and_mail.mail.getCcAddr())
                                        + "\n" + "Subject: " + account_and_mail.mail.getSubject() + "\n\n"
                                        + account_and_mail.mail.getContent() + "\n");
                    }
                }

                if (abort_this_try == false) {
                    generalServices.removeSentMail(account_and_mail.mail);

                    try {
                        final Address from_addr = new InternetAddress(account_and_mail.account.getEmail());
                        final Address[] to_addr = getAddressesFromString(account_and_mail.mail.getToAddr());
                        final Address[] cc_addr = getAddressesFromString(account_and_mail.mail.getCcAddr());

                        manager.sendMessage(from_addr, to_addr, cc_addr, account_and_mail.mail.getSubject(),
                                account_and_mail.mail.getContent());

                    } catch (final MessagingException ex) {
                        log.warn(ex.toString());

                        generalServices.sendInternalMailByAccount(account_and_mail.account,
                                "It was not possible to send your mail",
                                "An exception occured while sending your mail:\n" + ex.toString()
                                        + "\n\nthis mail has not been sent:\n-----\n" + "From: "
                                        + account_and_mail.account.getEmail() + "\n" + "To: "
                                        + account_and_mail.mail.getToAddr() + "\n" + "Cc: "
                                        + ((account_and_mail.mail.getCcAddr() == null) ? ""
                                                : account_and_mail.mail.getCcAddr())
                                        + "\n" + "Subject: " + account_and_mail.mail.getSubject() + "\n\n"
                                        + account_and_mail.mail.getContent() + "\n");

                    } finally {
                        try {
                            manager.disconnectRelay();
                        } catch (MessagingException ex) {
                            log.error(ex.toString());
                        }
                    }
                }
            } finally {
                synchronized (userIdsProcessing) {
                    if (should_remove_user_id_processing && userIdsProcessing.contains(user.getId()))
                        userIdsProcessing.remove(user.getId());
                }
            }
        }

    } finally {
        synchronized (new_mails_working_sync) {
            new_mails_working = false;
        }
    }
}

From source file:com.mobileman.projecth.business.messages.MessageServiceTest.java

/**
 * /*from  www  . ja v a 2 s . c  o  m*/
 * @throws Exception
 */
@Test
public void sendMessageWithCopy() throws Exception {

    User pat1 = userService.findUserByLogin("sysuser1");
    assertNotNull(pat1);
    User pat2 = userService.findUserByLogin("sysuser2");
    assertNotNull(pat2);

    List<Message> messagesOld = messageService.findAll();

    messageService.sendMessage(pat1.getId(), pat2.getId(), "Hallo pat2", "How are you?", true);

    List<Message> messages = messageService.findAll();
    assertEquals(messagesOld.size() + 1, messages.size());
    Message message = messages.get(messages.size() - 1);
    assertEquals(pat1.getId(), message.getSender().getId());
    assertEquals(pat2.getId(), message.getReceiver().getId());

    List<WiserMessage> mailMessages = wiser.getMessages();
    assertEquals(2, mailMessages.size());
    assertEquals(new InternetAddress("nachrichten@projecth.com"),
            mailMessages.get(0).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("doc1@projecth.com"),
            mailMessages.get(0).getMimeMessage().getRecipients(javax.mail.Message.RecipientType.TO)[0]);
    assertEquals("Hallo pat2", mailMessages.get(0).getMimeMessage().getSubject());

    Object mp = MimeMultipart.class.cast(mailMessages.get(0).getMimeMessage().getContent()).getBodyPart(0)
            .getContent();

    assertEquals(new InternetAddress("nachrichten@projecth.com"),
            mailMessages.get(1).getMimeMessage().getFrom()[0]);
    assertEquals(new InternetAddress("pat1@projecth.com"),
            mailMessages.get(1).getMimeMessage().getRecipients(javax.mail.Message.RecipientType.TO)[0]);
    assertEquals("Hallo pat2", mailMessages.get(1).getMimeMessage().getSubject());
}