package com.test.mail; import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class Sendmail { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { try { Properties prop = new Properties(); prop.setProperty("mail.host", "mail.creditharmony.cn"); prop.setProperty("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.auth", "true"); prop.setProperty("mail.smtp.starttls.enable", "true"); //使用JavaMail发送邮件的5个步骤 /** * 方式一: */ /* //1、创建session Session session = Session.getDefaultInstance(prop, null); //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 session.setDebug(true); //2、通过session得到transport对象 Transport ts = session.getTransport(); //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。 ts.connect("mail.creditharmony.cn", "PMS", "密码"); //4、创建邮件 Message message = createSimpleMail(session); //5、发送邮件 ts.sendMessage(message, message.getAllRecipients()); ts.close(); */ /** * 方式二: */ //创建session,并进行账号身份验证 ,SimpleAuthenticator身份验证的工具类;注:SimpleAuthenticator实例化时user不带后缀,即PMS,而非PMS@creditharmony.cn Session session = Session.getInstance(prop, new SimpleAuthenticator("PMS", "密码")); // Session session = Session.getInstance(prop, new Authenticator(){ // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication("PMS", "密码"); // }}); //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 session.setDebug(true); //4、创建邮件 Message message = createSimpleMail(session); Transport.send(message); } catch (Exception e) { e.printStackTrace(); } } public static MimeMessage createSimpleMail(Session session)throws Exception { //创建邮件对象 MimeMessage message = new MimeMessage(session); //指明邮件的发件人,发件人即是PMS@creditharmony.cn message.setFrom(new InternetAddress("PMS@creditharmony.cn")); //指明邮件的收件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress("yanhuiqu@creditharmony.cn")); //发给多个人 // message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("yanhuiqu@creditharmony.cn"),new InternetAddress("fanleisun@creditharmony.cn")}); //抄送 // message.setRecipient(Message.RecipientType.CC, new InternetAddress("yanhuiqu@creditharmony.cn")); //邮件的标题 message.setSubject("只包含文本的简单邮件"); //邮件的文本内容 message.setContent("测试,你好啊!", "text/html;charset=UTF-8"); //返回创建好的邮件对象 return message; } }
身份验证类:SimpleAuthenticator
package com.test.mail; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class SimpleAuthenticator extends Authenticator { private String user; private String pwd; public SimpleAuthenticator(String user, String pwd) { this.user = user; this.pwd = pwd; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pwd); } }