看这个之前,首先确定你拥有了发送邮件的账号以及授权码,(PS:授权码不是密码,是开通pop3服务,可自行百度)
直接上代码,必要信息有所隐藏,所以请勿照搬,请多看注释!!!多看注释!!!多看注释!!!
所使用的jar——pom.xml中引用,若不是可以 点击下载——> 程序中使用的jar mail.jar 【完全免费】
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
import java.util.Properties;
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;
import javax.mail.internet.MimeMessage.RecipientType;
/**
* description:容易导错包,需要注意
* @author 狼芒
* String receiver:收件人邮箱账号
* String activationCode:发送的激活码(或者内容)
*/
public class SentEmail {
public String sentEmail(String receiver,String activationCode) {
String result = "success sent to: "+receiver+"\tabout:\t"+activationCode;
// 得到session
Properties props = new Properties();
// props.setProperty("mail.host", "smtp.163.com");
props.setProperty("mail.host", "smtp.qq.com");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.auth", "true");//开启认证
props.setProperty("mail.debug", "true");//启用调试
props.setProperty("mail.smtp.timeout", "1000");//设置链接超时
props.setProperty("mail.smtp.port", "465");//设置端口
props.setProperty("mail.smtp.socketFactory.port", "465");//设置ssl端口
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 设置账号以及授权码
return new PasswordAuthentication("***账号***", "****授权码***");
}
};
Session session = Session.getInstance(props, auth);
/*
* 2、创建MimeMessage
*/
MimeMessage msg = new MimeMessage(session);
try {
// 设置发件人
msg.setFrom(new InternetAddress("***发送人账号**@qq.com","**可以给自己起个别名**"));
// 设置收件人
msg.setRecipients(RecipientType.TO, receiver);
// 设置抄送---允许围观
// msg.setRecipients(RecipientType.CC, "*********@qq.com");
// 设置暗送---在别人不知道的情况下发送到这里
// msg.setRecipients(RecipientType.BCC, "***********@qq.com");
// 设置标题
msg.setSubject("设置副标题");
// 设置内容
msg.setContent(activationCode,"text/html;charset=utf-8");
//发送邮件
Transport.send(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
result = e.getMessage();
e.printStackTrace();
}
return result;
}
}