Skip to content

Instantly share code, notes, and snippets.

@froop
Created February 17, 2012 14:33
Show Gist options
  • Save froop/1853812 to your computer and use it in GitHub Desktop.
Save froop/1853812 to your computer and use it in GitHub Desktop.
[Java][Servlet] メール送信機能(複数メール・単一接続)&受信テスト
<Context>
<Resource name="mail/Session" auth="Container"
type="javax.mail.Session"
mail.smtp.host="localhost"
mail.from="[email protected]"
mail.debug="false"
/>
<!--
<Resource name="mail/Session" auth="Container"
type="javax.mail.Session"
mail.smtp.host="smtp.gmail.com"
mail.smtp.port="587"
mail.smtp.auth="true"
mail.smtp.starttls.enable="true"
mail.from="[email protected]"
mail.debug="true"
/>
-->
</Context>
mail.pop3.host=localhost
mail.debug=false
public interface MailSender extends Closeable {
void connect() throws IOException;
void send(String address, String subject, String body);
}
import javax.mail.*;
public class MailSenderImpl implements MailSender {
private final Session session;
private final Transport transport;
public MailSenderImpl(Session session) {
this.session = session;
try {
this.transport = session.getTransport("smtp");
} catch (NoSuchProviderException e) {
throw new RuntimeException(e);
}
}
@Override
public void connect() throws IOException {
try {
transport.connect();
} catch (MessagingException e) {
throw new IOException(e);
}
}
@Override
public void send(String address, String subject, String body) {
try {
MimeMessage message = createMessage(address, subject, body);
transport.sendMessage(message, message.getAllRecipients());
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private MimeMessage createMessage(String address, String subject, String body)
throws MessagingException {
final String charset = "ISO-2022-JP";
MimeMessage message = new MimeMessage(session);
message.setRecipients(Message.RecipientType.TO,
new InternetAddress[] {new InternetAddress(address)});
message.setSubject(subject, charset);
message.setText(body, charset);
return message;
}
@Override
public void close() throws IOException {
try {
transport.close();
} catch (MessagingException e) {
throw new IOException(e);
}
}
}
public class MailSenderTest {
private MailTestHelper mail1;
private MailTestHelper mail2;
private MailTestHelper mail3;
@Before
public void setUp() throws Exception {
Session pop3 = createMailSession("/mail/MailPop3.properties", "user1", "user1");
mail1 = new MailTestHelper(pop3, "[email protected]", "件名test1");
mail2 = new MailTestHelper(pop3, "[email protected]", "件名test2");
mail3 = new MailTestHelper(pop3, "[email protected]", "件名test1");
deleteMail();
}
@After
public void tearDown() throws Exception {
deleteMail();
}
private void deleteMail() {
mail1.delete();
mail2.delete();
mail3.delete();
}
@Test
public void testMailSender() throws IOException {
MailSender sender = new MailSenderImpl(
createMailSession("/mail/MailSmtp.properties", null, null));
sender.connect();
try {
sender.send(mail1.getAddress(), mail1.getSubject(), "本文test1\n2行目");
sender.send(mail2.getAddress(), mail2.getSubject(), "本文test2");
sender.send(mail3.getAddress(), mail3.getSubject(), "本文test3");
} finally {
sender.close();
}
assertEquals("本文test1\r\n2行目", mail1.getContent());
assertEquals("本文test2", mail2.getContent());
assertEquals("本文test3", mail3.getContent());
}
private Session createMailSession(String path, final String user,
final String password) {
Properties props = loadProperties(path);
if (StringUtils.isEmpty(user)) {
return Session.getDefaultInstance(props);
} else {
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
};
return Session.getInstance(props, auth);
}
}
private Properties loadProperties(String propPath) {
try {
Properties res = new Properties();
res.load(getClass().getResourceAsStream(propPath));
return res;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public class MailServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Session session = lookupMailSession();
MailSender sender = new MailSenderImpl(session);
sender.connect();
try {
sender.send("[email protected]", "件名test1", "本文test1");
sender.send("[email protected]", "件名test2", "本文test2");
} finally {
sender.close();
}
}
private Session lookupMailSession() throws ServletException {
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
return (Session) envCtx.lookup("mail/Session");
} catch (NamingException e) {
throw new ServletException(e);
}
}
}
mail.smtp.host=localhost
[email protected]
mail.debug=true
#mail.smtp.host=smtp.gmail.com
#mail.smtp.port=587
#mail.smtp.auth=true
#mail.smtp.starttls.enable=true
#[email protected]
#mail.debug=true
public class MailTestHelper {
// POP3 polling (Millisec)
private static final int TIMEOUT = 1000 * 10;
private final static int WAIT = 500;
private final Session session;
private final String address;
private final String subject;
public MailTestHelper(Session session, String address, String subject) {
this.session = session;
this.address = address;
this.subject = subject;
}
public void delete() {
handleMessages(Folder.READ_WRITE, true, new MessageHandler() {
public void handle(Message message) throws Exception {
message.setFlag(Flags.Flag.DELETED, true);
}
});
}
public String getContent() {
List<String> contents = pollingMessages(TIMEOUT, WAIT);
assertEquals(1, contents.size());
return contents.get(0);
}
private List<String> pollingMessages(int timeoutMillisec, int waitMillisec) {
MessageGetHandler handler = new MessageGetHandler();
final int countMax = timeoutMillisec / waitMillisec;
for (int i = 0; i < countMax; i++) {
try {
Thread.sleep(waitMillisec);
handleMessages(Folder.READ_ONLY, false, handler);
} catch (InterruptedException e) {
break;
}
if (handler.getSize() > 0) {
break;
}
}
return handler.getContents();
}
private class MessageGetHandler implements MessageHandler {
private final List<String> contents = new ArrayList<String>();
public void handle(Message message) throws Exception {
String res = message.getContent().toString();
contents.add(res.replaceAll("(\\r\\n){3}$", ""));
}
public List<String> getContents() {
return new ArrayList<String>(contents);
}
public int getSize() {
return contents.size();
}
}
private interface MessageHandler {
void handle(Message message) throws Exception;
}
private void handleMessages(int openMode, boolean expunge,
MessageHandler handler) {
Store store = null;
Folder folder = null;
try {
store = session.getStore("pop3");
store.connect();
folder = store.getFolder("INBOX");
folder.open(openMode);
handleMessages(folder, handler);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (folder != null) {
folder.close(expunge);
}
if (store != null) {
store.close();
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
private void handleMessages(Folder folder, MessageHandler handler)
throws Exception {
for (Message message : folder.getMessages()) {
if (!subject.equals(message.getSubject())) {
continue;
}
if (!address.equals(getAddressTo(message))) {
continue;
}
handler.handle(message);
}
}
private String getAddressTo(Message message) throws MessagingException {
final Address[] addresses = message.getRecipients(RecipientType.TO);
assertEquals(1, addresses.length);
return ((InternetAddress) addresses[0]).getAddress();
}
public String getAddress() {
return address;
}
public String getSubject() {
return subject;
}
}
@froop
Copy link
Author

froop commented Feb 28, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment