メール送受信のテストをJUnitを使ってやってみる
SMTP、POP、IMAPを使用したメールの送受信テストを
JavaMailを使ってJavaで実装してみました。見よう見まねで。
JUnitから実行して、テストの正否を確認するコードを公開してみます。
import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import junit.framework.TestCase; public class MailTest extends TestCase { String fromName; String user; String password; String hostname; Properties propSmtp; Properties propPop3; Properties propImap; InternetAddress toAddress; InternetAddress fromAddress; Session session; protected void setUp(){ try{ toAddress = new InternetAddress("for@example.com"); fromAddress = new InternetAddress("bar@example.com", "fromUser"); }catch(AddressException e){ e.printStackTrace(); }catch(UnsupportedEncodingException e){ e.printStackTrace(); } user = "my user"; password = "my password"; hostname = "mailhost"; propSmtp = new Properties(); propSmtp.put("mail.smtp.host", hostname); propSmtp.put("mail.host", hostname); propSmtp.put("mail.smtp.connectiontimeout", "60000"); propSmtp.put("mail.smtp.timeout", "60000"); propPop3 = new Properties(); propPop3.setProperty("mail.pop3.host", hostname); propPop3.setProperty("mail.pop3.connectiontimeout", "60000"); propPop3.setProperty("mail.pop3.timeout", "60000"); propImap = new Properties(); propImap.setProperty("mail.imap.host", hostname); propImap.setProperty("mail.imap.connectiontimeout", "60000"); propImap.setProperty("mail.imap.timeout", "60000"); } protected Session createSession(Properties prop){ Session session = Session.getInstance(prop); session.setDebug(true); return session; } public void testSmtp(){ try{ session = createSession(propSmtp); MimeMessage message = new MimeMessage(session); message.setRecipient(Message.RecipientType.TO, toAddress); message.setFrom(fromAddress); message.setSubject("smtp", "ISO-2022-JP"); message.setContent("これはSMTPのテストメールです", "text/plain; charset=iso-2022-jp"); message.setHeader("Content-Transfer-Encoding", "7bit"); Transport.send(message); }catch(MessagingException e){ e.printStackTrace(); fail(); } } public void testPop3(){ try{ session = createSession(propPop3); Store store = session.getStore("pop3"); store.connect(user, password); assertTrue(store.isConnected()); store.close(); }catch(NoSuchProviderException e){ e.printStackTrace(); fail(); }catch(MessagingException e){ e.printStackTrace(); fail(); } } public void testImap(){ try{ session = createSession(propImap); Store store = session.getStore("imap"); store.connect(user, password); assertTrue(store.isConnected()); store.close(); }catch(NoSuchProviderException e){ e.printStackTrace(); fail(); }catch(MessagingException e){ e.printStackTrace(); fail(); } } }