doortts doortts 2013-04-03
email sender: rebuild Email send feature with play-email plugins
- replace apache commons to Play-2-Mailplugin
see: https://github.com/schleichardt/Play-2-Mailplugin

- add email send test
@26d0ab17b29fcdd868975c07ad33b6b3451fdab7
app/controllers/SiteApp.java
--- app/controllers/SiteApp.java
+++ app/controllers/SiteApp.java
@@ -4,15 +4,15 @@
 import java.util.List;
 import java.util.Map;
 
-import org.apache.commons.mail.EmailException;
+import org.apache.commons.mail.*;
 
 import models.Project;
 import models.User;
+import org.apache.commons.mail.SimpleEmail;
 import play.Configuration;
 import play.mvc.Controller;
 import play.mvc.Result;
 import utils.Constants;
-import utils.Mailer;
 
 import views.html.site.setting;
 import views.html.site.mail;
@@ -21,35 +21,30 @@
 
 import com.avaje.ebean.Page;
 import static play.data.Form.form;
+import info.schleichardt.play2.mailplugin.Mailer;
 
 public class SiteApp extends Controller {
-
-    public static Result sendMail() {
-        Mailer email = new Mailer(play.Play.application());
+    public static Result sendMail() throws EmailException{
+        SimpleEmail email = new SimpleEmail();
 
         Map<String, String[]> formData = request().body().asFormUrlEncoded();
-        email.addFrom(utils.HttpUtil.getFirstValueFromQuery(formData, "from"));
+        email.setFrom(utils.HttpUtil.getFirstValueFromQuery(formData, "from"));
         email.setSubject(utils.HttpUtil.getFirstValueFromQuery(formData, "subject"));
-        email.addRecipient(utils.HttpUtil.getFirstValueFromQuery(formData, "to"));
+        email.addTo(utils.HttpUtil.getFirstValueFromQuery(formData, "to"));
+        email.setMsg(utils.HttpUtil.getFirstValueFromQuery(formData, "body"));
+        email.setCharset("utf-8");
 
         String errorMessage = null;
         boolean sended = false;
-        try {
-            email.send(utils.HttpUtil.getFirstValueFromQuery(formData, "body"));
-            sended = true;
-        } catch (EmailException e) {
-            errorMessage = e.toString();
-            if (e.getCause() != null) {
-               errorMessage += "<br/>Caused by: " + e.getCause();
-            }
-        }
-
+        String result = Mailer.send(email);
+        System.out.println(">>>" + result);
+        sended = true;
         return writeMail(errorMessage, sended);
     }
 
     public static Result writeMail(String errorMessage, boolean sended) {
         Configuration config = play.Play.application().configuration();
-        List<String> notConfiguredItems = new ArrayList<String>();
+        List<String> notConfiguredItems = new ArrayList<>();
         String[] requiredItems = {"smtp.host", "smtp.user", "smtp.password"};
         for(String key : requiredItems) {
             if (config.getString(key) == null) {
@@ -57,13 +52,9 @@
             }
         }
 
-        String sender = config.getString("smtp.user");
+        String sender = config.getString("smtp.user") + "@" + config.getString("smtp.domain");
 
         return ok(mail.render("title.sendMail", notConfiguredItems, sender, errorMessage, sended));
-    }
-
-    public static Result writeMail() {
-        return writeMail(null, false);
     }
 
     public static Result setting() {
 
app/utils/Mailer.java (deleted)
--- app/utils/Mailer.java
@@ -1,239 +0,0 @@
-package utils;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.mail.internet.AddressException;
-import javax.mail.internet.InternetAddress;
-
-import org.apache.commons.mail.DefaultAuthenticator;
-import org.apache.commons.mail.Email;
-import org.apache.commons.mail.EmailException;
-import org.apache.commons.mail.HtmlEmail;
-import org.apache.commons.mail.MultiPartEmail;
-
-import play.Application;
-//import scala.actors.threadpool.Arrays;
-
-public class Mailer {
-    private final String smtpHost;
-    private final Integer smtpPort;
-    private final Boolean smtpSsl;
-    private final Boolean smtpTls;
-    private final String smtpUser;
-    private final String smtpPassword;
-
-    private final Map<String, List<String>> context = new HashMap<String, List<String>>();
-
-    public Mailer(Application app) {
-        smtpHost = app.configuration().getString("smtp.host");
-        smtpPort = app.configuration().getInt("smtp.port");
-        smtpSsl = app.configuration().getBoolean("smtp.ssl");
-        smtpTls = app.configuration().getBoolean("smtp.tls");
-        smtpUser = app.configuration().getString("smtp.user");
-        smtpPassword = app.configuration().getString("smtp.password");
-    }
-
-    public String send(String bodyText) throws EmailException {
-        return send(bodyText, "");
-    }
-
-    public String sendHtml(String bodyHtml) throws EmailException {
-        return send("", bodyHtml);
-    }
-
-    public String send(String bodyText, String bodyHtml) throws EmailException {
-        Email email = createEmailer(bodyText, bodyHtml);
-        email.setCharset(headOption("charset", "utf-8"));
-        email.setSubject(headOption("subject", ""));
-
-        for (String fromEmail : e("from")) {
-            email.setFrom(addressFrom(fromEmail), nameFrom(fromEmail)); }
-        for(String replyToEmail : e("replyTo")) {
-            email.addReplyTo(addressFrom(replyToEmail), nameFrom(replyToEmail)); }
-        for(String recipient: e("recipients")) {
-            email.addTo(addressFrom(recipient), nameFrom(recipient)); }
-        for(String ccRecipient: e("ccRecipients")) {
-            email.addCc(addressFrom(ccRecipient), nameFrom(ccRecipient)); }
-        for(String bccRecipient: e("bccRecipients")) {
-            email.addBcc(addressFrom(bccRecipient), nameFrom(bccRecipient)); }
-
-        Map<String, String> eheader = eheader();
-        Iterator<String> it = eheader.keySet().iterator();
-        while(it.hasNext()) {
-            String name = it.next();
-            String value = eheader.get(name);
-            email.addHeader(name, value);
-        }
-        email.setHostName(smtpHost);
-        if (smtpPort != null) {
-            email.setSmtpPort(smtpPort);
-        }
-        if (smtpSsl != null) {
-            email.setSSL(smtpSsl);
-        }
-        if (smtpTls != null) {
-            email.setTLS(smtpTls);
-        }
-        email.setAuthenticator(new DefaultAuthenticator(smtpUser, smtpPassword));
-        email.setDebug(false);
-        return email.send();
-    }
-
-    private String addressFrom(String emailAddress) {
-        return internetAddress(emailAddress).getAddress();
-    }
-
-    private String nameFrom(String emailAddress) {
-        return internetAddress(emailAddress).getPersonal();
-    }
-
-    private InternetAddress internetAddress(String emailAddress) {
-        InternetAddress iAddress = null;
-        if (emailAddress != null) {
-            try {
-                iAddress = new InternetAddress(emailAddress);
-            } catch (AddressException e) {
-                e.printStackTrace();
-            }
-        }
-        return iAddress;
-    }
-
-    private String headOption(String key, String defaultValue) {
-        List<String> values = e(key);
-        if (values.size() == 1) {
-            return values.get(0);
-        } else {
-            return defaultValue;
-        }
-    }
-
-    /**
-     * Creates an appropriate email object based on the content type.
-     *
-     * @param bodyText
-     * @param bodyHtml
-     * @return
-     * @throws EmailException
-     */
-    private Email createEmailer(String bodyText, String bodyHtml)
-            throws EmailException {
-        Email email = null;
-        if (bodyHtml == null || bodyHtml == "") {
-            email = new MultiPartEmail().setMsg(bodyText);
-        } else {
-            email = new HtmlEmail().setHtmlMsg(bodyHtml).setTextMsg(bodyText);
-        }
-        return email;
-    }
-
-    private Map<String, String> eheader() {
-        Map<String, String> headers = new HashMap<String, String>();
-        Iterator<String> it = context.keySet().iterator();
-        while(it.hasNext()) {
-            String key = it.next();
-            if(key.contains("header-")) {
-                headers.put(key.substring(7), context.get(key).get(0));
-            }
-        }
-        return headers;
-    }
-
-    /**
-     * extract parameter key from context
-     *
-     * @param key
-     */
-    private List<String> e(String key) {
-        return context.containsKey(key) ? context.get(key) : Collections.<String>emptyList();
-    }
-
-    /**
-     * Sets a subject for this email. It enables formatting of the providing
-     * string using Java's string formatter.
-     *
-     * @param subject
-     * @param args
-     *            TODO
-     */
-    public void setSubject(String... subject) {
-        context.put("subject", Arrays.asList(subject));
-    }
-
-    /**
-     * Adds an email recipient ("to" addressee).
-     *
-     * @param recipients
-     */
-    public void addRecipient(String... recipient) {
-        context.put("recipients", Arrays.asList(recipient));
-    }
-
-    /**
-     * Defines the sender of this email("from" address).
-     *
-     * @param from
-     */
-    public void addFrom(String from) {
-        context.put("from", list(from));
-    }
-
-    private List<String> list(String string) {
-        List<String> list = new ArrayList<String>();
-        list.add(string);
-        return list;
-    }
-
-    /**
-     * Adds an email recipient in CC.
-     *
-     * @param ccRecipients
-     */
-    public void addCc(String... ccRecipients) {
-        context.put("ccRecipients", Arrays.asList(ccRecipients));
-    }
-
-    /**
-     * Adds an email recipient in BCC.
-     *
-     * @param bccRecipients
-     */
-    public void addBcc(String... bccRecipients) {
-        context.put("bccRecipients", Arrays.asList(bccRecipients));
-    }
-
-    /**
-     * Defines the "reply to" email address.
-     *
-     * @param replyTo
-     */
-    public void setReplyTo(String replyTo) {
-        context.put("replyTo", list(replyTo));
-    }
-
-    /**
-     * Sets the charset for this email.
-     *
-     * @param charset
-     */
-    public void setCharset(String charset) {
-        context.put("charset", list(charset));
-    }
-
-    /**
-     * Adds a request header to this email message.
-     *
-     * @param key
-     * @param value
-     */
-    public void addHeader(String key, String value) {
-        context.put("header-" + key, list(value));
-    }
-
-}
conf/application.conf
--- conf/application.conf
+++ conf/application.conf
@@ -82,12 +82,19 @@
 # Mailer
 # ~~~~~~
 # You have to configure SMTP to send mails.
-
-smtp.host = "smtp.gmail.com"
+# Example settings, it assume that you use gamil smtp
+smtp.host = smtp.gmail.com
 smtp.port = 465
-smtp.ssl = "yes"
-smtp.user = "your mail address"
-smtp.password = "your mail password"
+smtp.ssl = true
+smtp.user = yourGmailId
+# Be careful!!!
+smtp.password = yourGmailPassword
+smtp.domain = gmail.com
+
+#true to use mock mailer for testing, false for using real mail server
+smtp.mock = true
+# optional, size of mail archive for tests, default: 5
+smtp.archive.size = 5
 
 # Akka
 akka.default-dispatcher.core-pool-size-max = 64
 
conf/play.plugins (added)
+++ conf/play.plugins
@@ -0,0 +1,1 @@
+15000:info.schleichardt.play2.mailplugin.MailPlugin(No newline at end of file)
conf/routes
--- conf/routes
+++ conf/routes
@@ -30,7 +30,7 @@
 
 # Site
 GET     /sites/setting                                  controllers.SiteApp.setting()
-GET     /sites/mail                                     controllers.SiteApp.writeMail()
+GET     /sites/mail                                     controllers.SiteApp.writeMail(errorMessage:String ?= "", sended:Boolean ?= false)
 POST    /sites/mail                                     controllers.SiteApp.sendMail()
 GET     /sites/userList                                 controllers.SiteApp.userList(pageNum: Int ?= 0, loginId: String ?= null)
 POST    /sites/userList                                 controllers.SiteApp.searchUser()
 
test/utils/MailSendTest.java (added)
+++ test/utils/MailSendTest.java
@@ -0,0 +1,68 @@
+package utils;
+
+import controllers.routes;
+import info.schleichardt.play2.mailplugin.Mailer;
+import junit.framework.Assert;
+import models.ModelTest;
+import org.apache.commons.mail.EmailException;
+import org.apache.commons.mail.SimpleEmail;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import play.test.FakeApplication;
+import play.test.Helpers;
+
+import java.util.Map;
+
+import static org.fest.assertions.Assertions.assertThat;
+import static play.test.Helpers.callAction;
+import static play.test.Helpers.fakeApplication;
+import static play.test.Helpers.running;
+
+/**
+ * User: doortts
+ * Date: 4/2/13
+ * Time: 4:49 PM
+ */
+public class MailSendTest {
+    protected static FakeApplication app;
+
+    @Before
+    public void startApp() {
+        app = Helpers.fakeApplication(Helpers.inMemoryDatabase());
+        Helpers.start(app);
+    }
+
+    @After
+    public void stopApp() {
+        Helpers.stop(app);
+    }
+
+    public static final String DEFAULT_TEXT_MESSAGE = "Dear recipient,\n\n\n" +
+            "this is the mailtext.\n\nsincerely sender\n\n" +
+            "테스트 메일입니다. 답장을 보내지 마세요. :)";
+    public static final String DEFAULT_HTML_MESSAGE = "<html><body style='background: red'><p>Hello</p></body></html>";
+    public static final String SENDER_LOCALHOST = "hiveproject.mail@gmail.com";
+    public static final String RECIPIENT_LOCALHOST = "nforge@nhn.com";
+    public static final String SUBJECT = "메일 발송 테스트입니다 - the subject of the email";
+    public static final String ATTACHEMENT_TXT_FILE_NAME = "the-text-file.txt";
+
+
+    @Test
+    public void testSendSimpleMail() throws Exception {
+        //Given
+        SimpleEmail email = new SimpleEmail();
+        email.setFrom(SENDER_LOCALHOST);
+        email.setSubject(SUBJECT);
+        email.addTo(RECIPIENT_LOCALHOST);
+        email.setMsg(DEFAULT_TEXT_MESSAGE);
+        email.setCharset("utf-8");
+
+        //When
+        Mailer.send(email);
+
+        //Then
+        assertThat(Mailer.history().get(0)).isEqualTo(email);
+    }
+}
Add a comment
List