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 (Deitel)
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 ...
Harvey M. Deitel, Paul J. Deitel-Java How to Program, 7th Edition-Prentice Hall (2007
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 ...
Quantitative Trading - How to Build Your Own Algorithmic Trading Business.
Bioinformatics-with-Python-Cookbook-Learn-how-to-use-modern-Python-bioinformatics-libraries-and-applications-to-do-cutting-edge-research-in-computational-biology.pdf
Java How to Program 11th edition英文版, 由EPUB转换而成, , 无密码保护,可复制文字 by Paul J. Deitel (Author), Harvey Deitel (Author)
Exploiting Software - How to Break Code.rar
how-to-use-cvs.pdf xiwang 对你有用
How To Use Photos To Sell More Online (Part I) 149 How To Use Photos To Sell More Online (Part II) 161 How To Use Photos To Sell More Online (Part III) 177 Design To Sell: 8 Useful Tips To Help ...
How to use SFTP (with client validation - public key authentication) The topic How to use SFTP (with client validation - password authentication) discusses the simplest form of client ...
Learn how to implement multithreading and reactive programming Build microservices in Java 9 Implement APIs to improve application code Authors Mayur Ramgir Mayur Ramgir has more than 16 years of ...
How to use epoll A complete example in C How to use epoll A complete example in C How to use epoll A complete example in C How to use epoll A complete example in C