当前位置:首页 > 开发 > 编程语言 > Java > 正文

Java SE: How to Use Java Mail to send e-mail

发表于: 2013-04-25   作者:DavyJones2010   来源:转载   浏览次数:
摘要: 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

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

Java SE: How to Use Java Mail to send e-mail

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
In this iOS SDK tutorial, I'll demonstrate how to allow your users to send e-mail without lea
1.须要的jar :mail.jar,activation.jar 2.QQ邮箱设置:设置 -帐户-开启服务:POP3/SMTP服务 3.注意
一、为什么要学javamail 大部分的web应用都需要集成邮件发送功能 例如: 1给新注册的用户发一封注册
Java API中有很多都使用了SecurityManager,这到底是什么玩意?最近看公司的产品的源码,也有不少Se
静态导入 l JDK 1.5 增加的静态导入语法用于导入指定类的某个静态属性值(方法)或全部静态属性值(方
昨天晚上开始学习传智播客的JAVA SE基础视频,到今天晚上已经把基础视频1-5看完了,因为之前段段续
1.知识体系图 java技术的主要分支方向: J2SE:java的标准版,提供基本的底层支持,图形界面,05年java十
1.HashSet底层使用HashMap实现的 当使用add方法将对象添加到Set当中时,实际上是将该对象作为底层所
http://www.softwaretestinghelp.com/css-selector-selenium-locator-selenium-tutorial-6/ In our
http://conkeyn.iteye.com/admin/blogs/454277 ftp://conkeyn.iteye.com/admin/blogs/454277 https:
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号