Search in sources :

Example 26 with InternetAddress

use of javax.mail.internet.InternetAddress in project spring-framework by spring-projects.

the class JavaMailSenderTests method javaMailSenderWithMimeMessagePreparators.

@Test
public void javaMailSenderWithMimeMessagePreparators() {
    MockJavaMailSender sender = new MockJavaMailSender();
    sender.setHost("host");
    sender.setUsername("username");
    sender.setPassword("password");
    final List<Message> messages = new ArrayList<>();
    MimeMessagePreparator preparator1 = new MimeMessagePreparator() {

        @Override
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("he@mail.org"));
            messages.add(mimeMessage);
        }
    };
    MimeMessagePreparator preparator2 = new MimeMessagePreparator() {

        @Override
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("she@mail.org"));
            messages.add(mimeMessage);
        }
    };
    sender.send(preparator1, preparator2);
    assertEquals("host", sender.transport.getConnectedHost());
    assertEquals("username", sender.transport.getConnectedUsername());
    assertEquals("password", sender.transport.getConnectedPassword());
    assertTrue(sender.transport.isCloseCalled());
    assertEquals(2, sender.transport.getSentMessages().size());
    assertEquals(messages.get(0), sender.transport.getSentMessage(0));
    assertEquals(messages.get(1), sender.transport.getSentMessage(1));
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) SimpleMailMessage(org.springframework.mail.SimpleMailMessage) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 27 with InternetAddress

use of javax.mail.internet.InternetAddress in project google-app-engine-jappstart by taylorleese.

the class MailService method sendActivationEmail.

/**
     * Sends the activation e-mail to the given user.
     *
     * @param user the user
     * @param locale the locale
     * @throws MessagingException messaging exception
     */
public final void sendActivationEmail(final UserAccount user, final String locale) throws MessagingException {
    final Properties props = new Properties();
    final Session session = Session.getDefaultInstance(props, null);
    final Message message = new MimeMessage(session);
    final Multipart multipart = new MimeMultipart();
    final MimeBodyPart htmlPart = new MimeBodyPart();
    final MimeBodyPart textPart = new MimeBodyPart();
    message.setFrom(new InternetAddress(getFromAddress()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
    message.setSubject(messageSource.getMessage("mail.subject", null, new Locale(locale)));
    textPart.setContent(messageSource.getMessage("mail.body.txt", new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/plain");
    htmlPart.setContent(messageSource.getMessage("mail.body.html", new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/html");
    multipart.addBodyPart(textPart);
    multipart.addBodyPart(htmlPart);
    message.setContent(multipart);
    Transport.send(message);
}
Also used : Locale(java.util.Locale) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) Properties(java.util.Properties) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 28 with InternetAddress

use of javax.mail.internet.InternetAddress in project Japid by branaway.

the class JapidMailer method send.

@SuppressWarnings("unchecked")
public static Future<Boolean> send(Object... args) {
    try {
        final HashMap<String, Object> infoMap = getInfoMap();
        // Body character set
        final String charset = (String) infoMap.get(CHARSET);
        // Headers
        final Map<String, String> headers = (Map<String, String>) infoMap.get(HEADERS);
        // Subject
        final String subject = (String) infoMap.get(SUBJECT);
        // xxx how to determine the method name???
        //            String templateName = (String) infoMap.get(METHOD);
        String templateNameBase = StackTraceUtils.getCaller();
        if (!templateNameBase.startsWith("notifiers")) {
            throw new RuntimeException("The emailers must be put in the \"notifiers\" package.");
        }
        //            if (templateNameBase.startsWith(NOTIFIERS)) {
        //                templateNameBase = templateNameBase.substring(NOTIFIERS.length());
        //            }
        //            if (templateNameBase.startsWith(CONTROLLERS)) {
        //                templateNameBase = templateNameBase.substring(CONTROLLERS.length());
        //            }
        //            templateNameBase = templateNameBase.substring(0, templateNameBase.indexOf("("));
        //            templateNameBase = templateNameBase.replace(".", "/");
        //            final Map<String, Object> templateHtmlBinding = new HashMap<String, Object>();
        //            final Map<String, Object> templateTextBinding = new HashMap<String, Object>();
        //            for (Object o : args) {
        //                List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o);
        //                for (String name : names) {
        //                    templateHtmlBinding.put(name, o);
        //                    templateTextBinding.put(name, o);
        //                }
        //            }
        String templateClassName = DirUtil.JAPIDVIEWS_ROOT + "._" + templateNameBase;
        String bodyHtml = null;
        Class tClass = Play.classloader.getClassIgnoreCase(templateClassName);
        if (tClass == null) {
            String templateFileName = templateClassName.replace('.', '/') + ".html";
            throw new RuntimeException("Japid Emailer: could not find a Japid template with the name of: " + templateFileName);
        } else if (JapidTemplateBase.class.isAssignableFrom(tClass)) {
            try {
                JapidController.render(tClass, args);
            } catch (JapidResult jr) {
                RenderResult rr = jr.getRenderResult();
                bodyHtml = rr.getContent().toString();
            }
        } else {
            throw new RuntimeException("The found class is not a Japid template class: " + templateClassName);
        }
        //    		System.out.println("email body: " + bodyHtml);
        // The rule is as follow: If we ask for text/plain, we don't care about the HTML
        // If we ask for HTML and there is a text/plain we add it as an alternative.
        // If contentType is not specified look at the template available:
        // - .txt only -> text/plain
        // else
        // -           -> text/html
        //            String contentType = (String) infoMap.get(CONTENT_TYPE);
        //            String bodyText = "";
        //            try {
        //                Template templateHtml = TemplateLoader.load(templateNameBase + ".html");
        //                bodyHtml = templateHtml.render(templateHtmlBinding);
        //            } catch (TemplateNotFoundException e) {
        //                if (contentType != null && !contentType.startsWith(TEXT_PLAIN)) {
        //                    throw e;
        //                }
        //            }
        ////
        //            try {
        //                Template templateText = TemplateLoader.load(templateName + ".txt");
        //                bodyText = templateText.render(templateTextBinding);
        //            } catch (TemplateNotFoundException e) {
        //                if (bodyHtml == null && (contentType == null || contentType.startsWith(TEXT_PLAIN))) {
        //                    throw e;
        //                }
        //            }
        // Content type
        // bran html for now
        //            if (contentType == null) {
        //                if (bodyHtml != null) {
        //                    contentType = TEXT_HTML;
        //                } else {
        //                    contentType = TEXT_PLAIN;
        //                }
        //            }
        // Recipients
        final List<Object> recipientList = (List<Object>) infoMap.get(RECIPIENTS);
        // From
        final Object from = infoMap.get(FROM);
        final Object replyTo = infoMap.get(REPLY_TO);
        Email email = null;
        if (infoMap.get(ATTACHMENTS) == null) {
            //                if (StringUtils.isEmpty(bodyHtml)) {
            //                    email = new SimpleEmail();
            //                    email.setMsg(bodyText);
            //                } else {
            HtmlEmail htmlEmail = new HtmlEmail();
            htmlEmail.setHtmlMsg(bodyHtml);
            //                    if (!StringUtils.isEmpty(bodyText)) {
            //                        htmlEmail.setTextMsg(bodyText);
            //                    }
            email = htmlEmail;
        //                }
        } else {
            //                if (StringUtils.isEmpty(bodyHtml)) {
            //                    email = new MultiPartEmail();
            //                    email.setMsg(bodyText);
            //                } else {
            HtmlEmail htmlEmail = new HtmlEmail();
            htmlEmail.setHtmlMsg(bodyHtml);
            //                    if (!StringUtils.isEmpty(bodyText)) {
            //                        htmlEmail.setTextMsg(bodyText);
            //                    }
            email = htmlEmail;
            //                }
            MultiPartEmail multiPartEmail = (MultiPartEmail) email;
            List<EmailAttachment> objectList = (List<EmailAttachment>) infoMap.get(ATTACHMENTS);
            for (EmailAttachment object : objectList) {
                multiPartEmail.attach(object);
            }
        }
        if (from != null) {
            try {
                InternetAddress iAddress = new InternetAddress(from.toString());
                email.setFrom(iAddress.getAddress(), iAddress.getPersonal());
            } catch (Exception e) {
                email.setFrom(from.toString());
            }
        }
        if (replyTo != null) {
            try {
                InternetAddress iAddress = new InternetAddress(replyTo.toString());
                email.addReplyTo(iAddress.getAddress(), iAddress.getPersonal());
            } catch (Exception e) {
                email.addReplyTo(replyTo.toString());
            }
        }
        if (recipientList != null) {
            for (Object recipient : recipientList) {
                try {
                    InternetAddress iAddress = new InternetAddress(recipient.toString());
                    email.addTo(iAddress.getAddress(), iAddress.getPersonal());
                } catch (Exception e) {
                    email.addTo(recipient.toString());
                }
            }
        } else {
            throw new MailException("You must specify at least one recipient.");
        }
        List<Object> ccsList = (List<Object>) infoMap.get(CCS);
        if (ccsList != null) {
            for (Object cc : ccsList) {
                email.addCc(cc.toString());
            }
        }
        List<Object> bccsList = (List<Object>) infoMap.get(BCCS);
        if (bccsList != null) {
            for (Object bcc : bccsList) {
                try {
                    InternetAddress iAddress = new InternetAddress(bcc.toString());
                    email.addBcc(iAddress.getAddress(), iAddress.getPersonal());
                } catch (Exception e) {
                    email.addBcc(bcc.toString());
                }
            }
        }
        if (!StringUtils.isEmpty(charset)) {
            email.setCharset(charset);
        }
        email.setSubject(subject);
        email.updateContentType(TEXT_HTML);
        if (headers != null) {
            for (String key : headers.keySet()) {
                email.addHeader(key, headers.get(key));
            }
        }
        // reset the infomap
        infos.remove();
        return Mail.send(email);
    } catch (EmailException ex) {
        throw new MailException("Cannot send email", ex);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Email(org.apache.commons.mail.Email) HtmlEmail(org.apache.commons.mail.HtmlEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) EmailAttachment(org.apache.commons.mail.EmailAttachment) RenderResult(cn.bran.japid.template.RenderResult) HtmlEmail(org.apache.commons.mail.HtmlEmail) MailException(play.exceptions.MailException) ExecutionException(java.util.concurrent.ExecutionException) UnexpectedException(play.exceptions.UnexpectedException) EmailException(org.apache.commons.mail.EmailException) EmailException(org.apache.commons.mail.EmailException) ArrayList(java.util.ArrayList) List(java.util.List) MailException(play.exceptions.MailException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 29 with InternetAddress

use of javax.mail.internet.InternetAddress in project translationstudio8 by heartsome.

the class MailUtils method getAddressName.

/**
	 * 用来取得 Email 地址的友好称呼。
	 * @param emailAddress
	 *            	Email 地址
	 * @return String
	 * 				例如: emailAddress="John &lt;john@test.com&gt;" 就返回 John。
	 */
public static String getAddressName(String emailAddress) {
    String result = "";
    if (emailAddress == null) {
        return result;
    }
    try {
        InternetAddress address = new InternetAddress(emailAddress);
        String text = address.getPersonal();
        if (text == null) {
            result = emailAddress;
        } else {
            result = text;
        }
    } catch (AddressException e) {
        e.printStackTrace();
        return emailAddress;
    }
    return result;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) AddressException(javax.mail.internet.AddressException)

Example 30 with InternetAddress

use of javax.mail.internet.InternetAddress in project translationstudio8 by heartsome.

the class MailUtils method getAddress.

/**
	 * 用来取得 Email 地址。
	 * @param emailAddress
	 *            the email address
	 * @return String
	 * 				例如: emailAddress="John &lt;john@test.com&gt;" 就返回 john@test.com
	 */
public static String getAddress(String emailAddress) {
    String result = "";
    if (emailAddress == null) {
        return result;
    }
    try {
        InternetAddress address = new InternetAddress(emailAddress);
        String text = address.getAddress();
        if (text == null) {
            result = emailAddress;
        } else {
            result = text;
        }
    } catch (AddressException e) {
        e.printStackTrace();
        return emailAddress;
    }
    return result;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) AddressException(javax.mail.internet.AddressException)

Aggregations

InternetAddress (javax.mail.internet.InternetAddress)255 MimeMessage (javax.mail.internet.MimeMessage)106 MessagingException (javax.mail.MessagingException)69 Session (javax.mail.Session)49 Properties (java.util.Properties)45 ArrayList (java.util.ArrayList)42 Address (javax.mail.Address)41 Message (javax.mail.Message)40 Date (java.util.Date)38 JavaMailInternetAddress (com.zimbra.common.mime.shim.JavaMailInternetAddress)36 AddressException (javax.mail.internet.AddressException)34 X509Certificate (java.security.cert.X509Certificate)32 MimeBodyPart (javax.mail.internet.MimeBodyPart)30 Test (org.junit.Test)29 IOException (java.io.IOException)26 MimeMultipart (javax.mail.internet.MimeMultipart)26 PolicyExpression (org.nhindirect.policy.PolicyExpression)18 HashMap (java.util.HashMap)17 CertificateResolver (org.nhindirect.stagent.cert.CertificateResolver)17 PolicyResolver (org.nhindirect.stagent.policy.PolicyResolver)17