1. Precondition
1) Import mail-1.4.1.jar for basic javax.mail api which can be found here
http://www.oracle.com/technetwork/java/javamail/index-138643.html
2) Import greenmail-1.3.1.jar for easy mail test which can be found here
http://www.icegreen.com/greenmail/
3) Import JUnit4 Library
2. A simple example for sending pure text email <Test passed!>
package edu.xmu.mail; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.junit.Before; import org.junit.Test; public class SendMail { private static final String SMTP_HOST_NAME = "smtp.gmail.com"; private static final String SMTP_AUTH_USER = "davyjones2010#gmail.com"; private static final String SMTP_AUTH_PWD = "*******"; private static final String SMTP_PORT_NUM = "465"; @Before public void setUp() { } @Test public void sendMail() { String[] fakeToList = { "554212185#qq.com", "kunlun0519#sohu.com" }; InternetAddress[] realToList = new InternetAddress[fakeToList.length]; String from = "davyjones2010#gmail.com"; String subject = "Hello World!"; String content = "This is a test email from java-mail"; Transport transport = null; // Set the host smtp address Properties properties = System.getProperties(); properties.put("mail.smtp.host", SMTP_HOST_NAME); properties.put("mail.smtp.user", SMTP_AUTH_USER); properties.put("mail.smtp.port", SMTP_PORT_NUM); properties.put("mail.smtp.socketFactory.port", SMTP_PORT_NUM); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.debug", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("javax.net.ssl.SSLSocketFactory", "false"); Authenticator auth = new SMTPAuthenticator(); Session session = Session.getDefaultInstance(properties, auth); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); for (int i = 0; i < fakeToList.length; i++) { realToList[i] = new InternetAddress(fakeToList[i]); } message.setRecipients(Message.RecipientType.TO, realToList); message.setSubject(subject); message.setContent(content, "text/plain"); // For HTML-Email // message.setContent(content, "text/html"); transport = session.getTransport("smtp"); transport.connect(SMTP_HOST_NAME, Integer.valueOf(SMTP_PORT_NUM) .intValue(), SMTP_AUTH_USER, SMTP_AUTH_PWD); transport.sendMessage(message, message.getAllRecipients()); System.out.println("Message sent successflly..."); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { transport.close(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private class SMTPAuthenticator extends Authenticator { @Override public PasswordAuthentication getPasswordAuthentication() { String username = SMTP_AUTH_USER; String password = SMTP_AUTH_PWD; return new PasswordAuthentication(username, password); } } }
3. A more complex example for sending email with attachment <Test passed!>
package edu.xmu.mail; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.junit.Before; import org.junit.Test; public class SendMail { private static final String SMTP_HOST_NAME = "smtp.gmail.com"; private static final String SMTP_AUTH_USER = "davyjones2010#gmail.com"; private static final String SMTP_AUTH_PWD = "******"; private static final String SMTP_PORT_NUM = "465"; @Before public void setUp() { } @Test public void sendMail() { String[] fakeToList = { "554212185#qq.com", "kunlun0519#sohu.com" }; InternetAddress[] realToList = new InternetAddress[fakeToList.length]; String from = "davyjones2010#gmail.com"; String subject = "Hello World!"; String content = "This is a test email from java-mail"; Transport transport = null; // Set the host smtp address Properties properties = System.getProperties(); properties.put("mail.smtp.host", SMTP_HOST_NAME); properties.put("mail.smtp.user", SMTP_AUTH_USER); properties.put("mail.smtp.port", SMTP_PORT_NUM); properties.put("mail.smtp.socketFactory.port", SMTP_PORT_NUM); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.debug", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("javax.net.ssl.SSLSocketFactory", "false"); Authenticator auth = new SMTPAuthenticator(); Session session = Session.getDefaultInstance(properties, auth); MimeMessage message = new MimeMessage(session); System.out.println("CurrentPath = " + ClassLoader.getSystemResource("") + "attachment.txt"); try { message.setFrom(new InternetAddress(from)); for (int i = 0; i < fakeToList.length; i++) { realToList[i] = new InternetAddress(fakeToList[i]); } message.setRecipients(Message.RecipientType.TO, realToList); message.setSubject(subject); // Create a multi-part message Multipart multipart = new MimeMultipart(); // Set part one -> plain text BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(content); multipart.addBodyPart(messageBodyPart); // Set part two -> attachment BodyPart attachmentBodyPart = new MimeBodyPart(); String fileName = ClassLoader.getSystemResource("").toString() .replaceAll("%20", " ").replaceAll("file:/", "") + "attachment.txt"; DataSource source = new FileDataSource(fileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); attachmentBodyPart.setFileName("attachment.txt"); multipart.addBodyPart(attachmentBodyPart); message.setContent(multipart); transport = session.getTransport("smtp"); transport.connect(SMTP_HOST_NAME, Integer.valueOf(SMTP_PORT_NUM) .intValue(), SMTP_AUTH_USER, SMTP_AUTH_PWD); transport.sendMessage(message, message.getAllRecipients()); System.out.println("Message sent successflly..."); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { transport.close(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private class SMTPAuthenticator extends Authenticator { @Override public PasswordAuthentication getPasswordAuthentication() { String username = SMTP_AUTH_USER; String password = SMTP_AUTH_PWD; return new PasswordAuthentication(username, password); } } }
P.S
Good resource to refer to:
1) https://java.net/projects/javamail/pages/Home
2) http://stackoverflow.com/questions/1990454/using-javamail-to-connect-to-gmail-smtp-server-ignores-specified-port-and-tries ---> Inspired me a lot in configure gmail smtp service
3) http://blog.csdn.net/zapldy/article/details/3971579 ---> A very detailed blog about Java Mail
4) http://704378737-qq-com.iteye.com/blog/796566 ---> A very detailed blog about Java Path
相关推荐
Think Java: How to Think Like a Computer Scientist by Allen B. Downey, Chris Mayfield 2016 | ISBN: 1491929561 Currently used at many colleges, universities, and high schools, this hands-on ...
本书是针对没有经验或没有经验的人的计算机科学和编程的简介。 它从最基本的概念开始,并在首次使用时仔细定义所有术语。
Sample04-Winforms: How to use OpenCVSharp in a WindowsForms application. Sample05: How to use OpenCVSharp in a WPF application. Sample06: How to use VideoCapture and WebCams. Sample07: How to access ...
《Java: How to Program, 9th Edition》是由Paul Deitel和Harvey Deitel合著的一本经典Java编程教程,适合初学者和有一定经验的程序员深入学习Java语言。这本书全面覆盖了Java的基础知识,进阶特性,以及面向对象...
Sample04-Winforms: How to use OpenCVSharp in a WindowsForms application. Sample05: How to use OpenCVSharp in a WPF application. Sample06: How to use VideoCapture and WebCams. Sample07: How to access ...
Sample04-Winforms: How to use OpenCVSharp in a WindowsForms application. Sample05: How to use OpenCVSharp in a WPF application. Sample06: How to use VideoCapture and WebCams. Sample07: How to access ...
面向初学者的Java编程简介。 它是为准备参加计算机科学高级进阶(AP)考试的学生量身定制的,但它是为想要学习Java的任何人而设计的。
### 量化交易:如何构建自己的算法交易业务 #### 核心知识点概述 本文将深入探讨《量化交易:如何构建自己的算法交易业务》一书中的核心知识点。本书由Ernest P. Chan撰写,作为一位在量化交易领域有着丰富经验的...
How-to-Use-SAMA5D2-GPIO-Under-Linux-00003293a.pdf
Think Perl 6: How to Think Like a Computer Scientist by Laurent Rosenfeld English | 8 May 2017 | ASIN: B0716P9W11 | 466 Pages | AZW3 | 1.02 MB Want to learn how to program and think like a computer ...
《Java如何编程,第7版-Prentice Hall》由Harvey M. Deitel和Paul J. Deitel联合撰写,是Java编程领域的一本经典教材,涵盖了Java语言的基础知识和一些进阶话题。该书不仅适合初学者,也适合作为有经验的程序员的...
然而,根据“how to use eclipse”这一标题,我将基于这一假设,提供Eclipse开发环境(IDE)的使用方法。 Eclipse是Java开发环境中广泛使用的一款集成开发工具,它是由Eclipse基金会维护的一个开源项目。Eclipse ...
Bioinformatics-with-Python-Cookbook-Learn-how-to-use-modern-Python-bioinformatics-libraries-and-applications-to-do-cutting-edge-research-in-computational-biology.pdf
Exploiting Software - How to Break Code.rar
### Think Java:如何像计算机科学家一样思考 #### 标题解析 - **Think Java** 这一标题直接指向了本书的核心内容,即通过学习 Java 编程语言来培养读者像计算机科学家一样的思维方式。这里提到的“像计算机科学家...