package itat.org.zttc.mail; import java.util.Properties; import javax.mail.Message; import javax.mail.Message.RecipientType; import javax.mail.Authenticator; 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; public class TestMail02 { public static void main(String[] args) { try { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); /** * 设置发送邮件的服务器,不同的邮箱服务器不一致,可以在邮箱的帮助中查询 */ props.setProperty("mail.host", "smtp.sina.com"); /** * 设置发送服务器验证,一些邮箱需要增加这个验证才能发送邮件 */ props.setProperty("mail.smtp.auth", "true"); /** * 当需要使用Transport.send发送时,需要将用户名和密码设置到Session中 */ Session session = Session.getDefaultInstance(props,new Authenticator() { /** * 通过Authenticator中 的getPasswordAuthentication的方法来
*设置邮箱的用户名和密码 */ @Override protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication("kh_itat", "kh1234"); } }); session.setDebug(true); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("kh_itat@sina.com")); msg.setRecipient(RecipientType.TO,new InternetAddress("ynkonghao@gmail.com")); msg.setSubject("一封邮件"); /** * 通过以下方式可以创建一个html的文档 */ msg.setContent("<h1 style='color:red'>这是一封邮件</h1>","text/html;
charset=utf-8"); /** * 使用Transport的static方法send发送邮件需要在Session创建时来确定访问的
*密码 */ Transport.send(msg); System.out.println("------------------------------------------"); Properties props1 = new Properties(); props1.setProperty("mail.transport.protocol", "smtp"); /** * 设置发送邮件的服务器,不同的邮箱服务器不一致,可以在邮箱的帮助中查询 */ props1.setProperty("mail.host", "smtp1.sohu.com"); /** * 设置发送服务器验证,一些邮箱需要增加这个验证才能发送邮件 */ props1.setProperty("mail.smtp.auth", "true"); /** * 当使用getDefaultInstance的时候,会查找Session是否在内存中已经存在,
*如果存在就不会再去 * 读取新的Properties中的配置,而是直接使用内存中已经存在的配置信息,
*所以此时可以不设置props * 都可以访问. * 所以如果在一个项目中可能会涉及到使用多个邮箱发送邮件,
*就不要使用getDefaultInstance来处理 * 在一些特殊的情况:如果邮箱验证此时只会通过一个邮箱发出邮件,就可以使用
*getDefaultInstance来处理 */ Session s2 = Session.getInstance(props1, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("kh_itat","kh1234"); } }); Message msg2 = new MimeMessage(s2); msg2.setFrom(new InternetAddress("kh_itat@sohu.com")); msg2.setRecipient(RecipientType.TO,new InternetAddress("kh_itat@sina
.com")); msg2.setSubject("一封发给自己的邮件"); /** * 通过以下方式可以创建一个html的文档 */ msg2.setContent("<h1 style='color:red'>这是一封发给自己的邮件</h1>",
"text/html;charset=utf-8"); /** * 使用Transport的static方法send发送邮件需要在Session创建时来确定访问的
*密码 */ Transport.send(msg2); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }