需求:使用Java来实现‘邮件发送’功能
发送方:QQ邮箱
接收方:126邮箱
环境:myeclipse、jdk1.8、mail包、maven
项目下载:(技术群会员,方可下载)(全文最后申请入群即可成为会员)
开发步骤
1:新建maven工程,如下:
2:开通QQ邮箱的POP3/IMAP/SMTP服务:
3:在maven工程中,导入发送邮件所需jar包:
<dependencies>
<!-- java发送邮件jar包 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies>
4:添加发送邮件的工具类:
/**
* 邮件发送
* QQ邮箱--->126邮箱
* @author likang
*/
public class SendEmailManger extends Thread {
private String mailAdr;
private String content;
private String subject;
public SendEmailManger(String mailAdr, String subject, String content) {
super();
this.mailAdr = mailAdr;
this.subject = subject;
this.content = content;
}
@Override
public void run() {
super.run();
try {
sendMail(mailAdr, subject, content);
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendMail(String mailAdr, String subject, String content) throws Exception {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
final Properties props = new Properties();
// 表示SMTP发送邮件,需要进行身份验证
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");
// smtp登陆的账号、密码 ;需开启smtp登陆
props.setProperty("mail.debug", "true");
props.put("mail.user", "你的QQ邮箱地址");
props.put("mail.password", "QQ获取的授权码");
// 特别需要注意,要将ssl协议设置为true,否则会报530错误
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
try {
InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
message.setFrom(form);
// 设置收件人
InternetAddress to = new InternetAddress(mailAdr);
message.setRecipient(RecipientType.TO, to);
// 设置抄送
// InternetAddress cc = new InternetAddress("591566764@qq.com");
// message.setRecipient(RecipientType.CC, cc);
// 设置密送,其他的收件人不能看到密送的邮件地址
// InternetAddress bcc = new InternetAddress("mashen@163.com");
// message.setRecipient(RecipientType.CC, bcc);
// 设置邮件标题
message.setSubject(subject);
// 设置邮件的内容体
message.setContent(content, "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SendEmailManger d = new SendEmailManger("邮件接收者地址", "码神联盟", "尊敬的码神你好: <br/><br/><a href='https://mp.weixin.qq.com/s/BJR5vfgWIyEDN88PU3g6xA' style='color:red;'>微信公众号码神联盟真不错....</a>");
d.start();
}
}
5:验证结果: