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:com.brienwheeler.svc.email.impl.EmailService.java

/**
 * This is a private method (rather than having the public template method
 * call the public non-template method) to prevent inaccurate MonitoredWork
 * operation counts.// w  w w.jav  a2s. c  o  m
 * 
 * @param recipient
 * @param subject
 * @param body
 */
private void doSendEmail(EmailAddress recipient, String subject, String body) {
    ValidationUtils.assertNotNull(recipient, "recipient cannot be null");
    subject = ValidationUtils.assertNotEmpty(subject, "subject cannot be empty");
    body = ValidationUtils.assertNotEmpty(body, "body cannot be empty");

    try {
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress(fromAddress.getAddress()));
        message.setRecipients(Message.RecipientType.TO, recipient.getAddress());
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
        log.info("sent email to " + recipient.getAddress() + " (" + subject + ")");
    } catch (MessagingException e) {
        throw new ServiceOperationException(e);
    }
}

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

@Test
public void testPopulateResubscribeMessage() 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",
            "Resubscribe Successful", "resubscribe_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Resubscribe Successful", message.getSubject());
    Assert.assertEquals(_RESUBSCRIBE_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.maydesk.base.util.PDUtil.java

/**
 * Validate the form of an email address.
 * /*from ww  w  .  ja v a2 s . co m*/
 * <P>
 * Return <tt>true</tt> only if
 * <ul>
 * <li> <tt>aEmailAddress</tt> can successfully construct an
 * {@link javax.mail.internet.InternetAddress}
 * <li>when parsed with "@" as delimiter, <tt>aEmailAddress</tt> contains
 * two tokens which satisfy
 * {@link hirondelle.web4j.util.Util#textHasContent}.
 * </ul>
 * 
 * <P>
 * The second condition arises since local email addresses, simply of the
 * form "<tt>albert</tt>", for example, are valid for
 * {@link javax.mail.internet.InternetAddress}, but almost always undesired.
 */
public static boolean isValidEmailAddress(String aEmailAddress) {
    if (aEmailAddress == null)
        return false;
    boolean result = true;
    try {
        InternetAddress emailAddr = new InternetAddress(aEmailAddress);
        if (!hasNameAndDomain(aEmailAddress)) {
            result = false;
        }
    } catch (AddressException ex) {
        result = false;
    }
    return result;
}

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

@Test
public void testCaseInsensitive() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/* w  w w .ja va2 s  . c  om*/

    Mail mail = new MockMail();

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

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

    message.saveChanges();

    mail.setMessage(message);

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

    recipients.add(new MailAddress("TEST2@EXAMPLE.COM"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(1, result.size());
    assertTrue(result.contains(new MailAddress("TEST2@EXAMPLE.COM")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
}

From source file:com.waveerp.sendMail.java

public void sendMsgSSL(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc) throws Exception {

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.socketFactory.port", strPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", strPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }// w  ww  . j  a  va  2 s.  c om
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(strSource));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination));
        message.setSubject(strSubject);
        message.setText(strMsg);

        Transport.send(message);

        //System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

    //log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass );

}

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

public void send(ValueContext vc, Map bodyTemplateVars) throws IOException, AddressException,
        MessagingException, SendMailNoFromAddressException, SendMailNoRecipientsException {
    if (from == null)
        throw new SendMailNoFromAddressException("No FROM address provided.");

    if (to == null && cc == null && bcc == null)
        throw new SendMailNoRecipientsException("No TO, CC, or BCC addresses provided.");

    Properties props = System.getProperties();
    props.put("mail.smtp.host", host.getTextValue(vc));

    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage message = new MimeMessage(mailSession);

    if (headers != null) {
        List headersList = headers.getHeaders();
        for (int i = 0; i < headersList.size(); i++) {
            Header header = (Header) headersList.get(i);
            message.setHeader(header.getName(), header.getValue().getTextValue(vc));
        }/*  w w w .  ja  va2 s.  co  m*/
    }

    message.setFrom(new InternetAddress(from.getTextValue(vc)));

    if (replyTo != null)
        message.setReplyTo(getAddresses(replyTo.getValue(vc)));

    if (to != null)
        message.setRecipients(Message.RecipientType.TO, getAddresses(to.getValue(vc)));

    if (cc != null)
        message.setRecipients(Message.RecipientType.CC, getAddresses(cc.getValue(vc)));

    if (bcc != null)
        message.setRecipients(Message.RecipientType.BCC, getAddresses(bcc.getValue(vc)));

    if (subject != null)
        message.setSubject(subject.getTextValue(vc));

    if (body != null) {
        StringWriter messageText = new StringWriter();
        body.process(messageText, vc, bodyTemplateVars);
        message.setText(messageText.toString());
    }

    Transport.send(message);
}

From source file:com.flexive.shared.FxMailUtils.java

private static InternetAddress createAddress(String from)
        throws AddressException, UnsupportedEncodingException {
    final InternetAddress address = new InternetAddress(from);
    if (address.getPersonal() != null) {
        // encode name which is more likely to use non-ASCII characters
        address.setPersonal(address.getPersonal(), "UTF-8");
    }/* w w  w  .j ava 2 s  .  c  o  m*/
    return address;
}

From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java

@Override
public void sendMailWithPreviousMailContent(final MailMetaData mailMetaData, final String text,
        final Message previousMailMessage) {
    LOGGER.debug("Sending mail with content from previous mail(MailServiceImpl)");
    if (suppressMail) {
        return;// w w  w.  j  a  v a  2  s.com
    }
    setMailProperties();
    MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            if (null != mailMetaData.getCcAddresses() && mailMetaData.getCcAddresses().size() > 0) {
                setAddressToMessage(RecipientType.CC, mimeMessage, mailMetaData.getCcAddresses());
            }
            if (null != mailMetaData.getBccAddresses() && mailMetaData.getBccAddresses().size() > 0) {
                setAddressToMessage(RecipientType.BCC, mimeMessage, mailMetaData.getBccAddresses());
            }
            if (null != mailMetaData.getToAddresses() && mailMetaData.getToAddresses().size() > 0) {
                setAddressToMessage(RecipientType.TO, mimeMessage, mailMetaData.getToAddresses());
            }

            if (null != mailMetaData.getFromAddress()) {
                mimeMessage.setFrom(new InternetAddress(new StringBuilder().append(mailMetaData.getFromName())
                        .append(MailConstants.LESS_SYMBOL).append(mailMetaData.getFromAddress())
                        .append(MailConstants.GREATER_SYMBOL).toString()));
            }

            if (null != mailMetaData.getSubject() && null != text) {
                mimeMessage.setSubject(mailMetaData.getSubject());
            }

            if (null != text) {
                mimeMessage.setText(text);
            }

            // Create your new message part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(EphesoftStringUtil.concatenate(text, ORIGINAL_MAIL_MESSAGE));

            // Create a multi-part to combine the parts
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Create and fill part for the forwarded content
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(previousMailMessage.getDataHandler());

            // Add part to multi part
            multipart.addBodyPart(messageBodyPart);

            // Associate multi-part with message
            mimeMessage.setContent(multipart);

        }
    };
    try {
        mailSender.send(messagePreparator);
    } catch (MailException mailException) {
        LOGGER.error("Error while sending mail to configured mail account", mailException);
        throw new SendMailException(
                EphesoftStringUtil.concatenate("Error sending mail: ", mailMetaData.toString()), mailException);
    }
    LOGGER.info("mail sent successfully");
}

From source file:com.iana.dver.controller.LoginController.java

private void sendForgotPwdEmail(DverUsers dverUser, DverConfig dverConfig, UserLogin dverUserLogin)
        throws IOException, DocumentException, AddressException {

    try {/*from w w  w. ja v a  2  s.  c  om*/
        PdfReader reader = new PdfReader(
                servletContext.getResourceAsStream("/WEB-INF/email_templates/DVER_FORGOT_PWD_FORM.pdf"));

        File tempFile = File.createTempFile("DVER_FORGOT_PWD_" + dverUserLogin.getUserName(), ".pdf");

        PdfStamper filledOutForm = new PdfStamper(reader, new FileOutputStream(tempFile));
        AcroFields form = filledOutForm.getAcroFields();
        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date date = new Date();

        form.setField("topmostSubform[0].Page1[0].notif_dt[0]", dateFormat.format(date));
        form.setField("topmostSubform[0].Page1[0].contact_nm[0]",
                dverUser.getFname() + " " + dverUser.getLname());
        form.setField("topmostSubform[0].Page1[0].company[0]", dverUser.getCompanyName());
        form.setField("topmostSubform[0].Page1[0].address[0]", dverUser.getAddr1() + " " + dverUser.getAddr2());
        form.setField("topmostSubform[0].Page1[0].city[0]",
                dverUser.getCity() + ", " + dverUser.getState() + " " + dverUser.getZip());

        form.setField("topmostSubform[0].Page1[0].scac[0]", dverUser.getScac());
        form.setField("topmostSubform[0].Page1[0].pwd[0]", dverUserLogin.getPassword());

        filledOutForm.setFormFlattening(Boolean.TRUE);
        filledOutForm.close();

        DVERUtil.sendEmailWithAttachments("admin@dver.intermodal.org", "DVER - Password Recovery",
                new InternetAddress[] { new InternetAddress(dverUser.getEmail()) },
                "Please see attached to know your forgotten password.", tempFile);

        if (!dverUser.getEmail().equals(dverConfig.getEmail())) {

            PdfReader reader1 = new PdfReader(
                    servletContext.getResourceAsStream("/WEB-INF/email_templates/DVER_FORGOT_PWD_FORM.pdf"));
            File tempFile1 = File.createTempFile("DVER_FORGOT_PWD_NOTIF_" + dverUserLogin.getUserName(),
                    ".pdf");

            PdfStamper filledOutForm1 = new PdfStamper(reader1, new FileOutputStream(tempFile1));
            AcroFields form1 = filledOutForm1.getAcroFields();

            form1.setField("topmostSubform[0].Page1[0].notif_dt[0]", dateFormat.format(date));
            form1.setField("topmostSubform[0].Page1[0].contact_nm[0]",
                    dverConfig.getFname() + " " + dverConfig.getLname());
            form1.setField("topmostSubform[0].Page1[0].company[0]", dverUser.getCompanyName());
            form1.setField("topmostSubform[0].Page1[0].address[0]",
                    dverUser.getAddr1() + " " + dverUser.getAddr2());
            form1.setField("topmostSubform[0].Page1[0].city[0]",
                    dverUser.getCity() + ", " + dverUser.getState() + " " + dverUser.getZip());

            form1.setField("topmostSubform[0].Page1[0].scac[0]", dverUser.getScac());
            form1.setField("topmostSubform[0].Page1[0].pwd[0]", dverUserLogin.getPassword());

            filledOutForm1.setFormFlattening(Boolean.TRUE);
            filledOutForm1.close();

            DVERUtil.sendEmailWithAttachments("admin@dver.intermodal.org", "DVER - Password Recovery",
                    new InternetAddress[] { new InternetAddress(dverConfig.getEmail()) },
                    "Please see attached to know your forgotten password.", tempFile1);
        }

        tempFile.deleteOnExit();

    } catch (Exception ex) {

        logger.error("Error in sendForgotPwdEmail....." + ex);

        DVERUtil.sendExceptionEmails("sendForgotPwdEmail method of LoginController \n " + ex);

    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailAnda(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {
    //Get properties object    
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }// w w w.  jav a  2s.  co m
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        //message.setContent(multipart);

        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        message.setContent(writer.toString(), "text/html");

        //send message  
        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}