发送邮件
1、前景知识
发送邮件使用SMTP协议,接收邮件使用POP3协议;
打开qq邮件传输通道
得到授权码
2、导入依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
3、简单邮件发送
实现代码:
package com.liu.study.mail;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SimpleMail {
//使用javaMail发送邮件的五个步骤
//1.创建定义整个环境的应用程序所需要的环境信息的Session对象
//2.通过session得到transport对象
//3.使用邮箱的用户名和授权码连上邮件服务器
//4.创建邮件
//5.发送邮件
public static void main(String[] args) throws Exception {
//1.创建定义整个环境的应用程序所需要的环境信息的Session对象
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.qq.com");
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auuth", "true");
//qq邮箱
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("邮箱名","授权码");
}
});
//开启session的debug模式
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","邮箱名","授权码");
//4.创建邮件
//写邮件
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("发件人邮箱"));
//指明收件人,现在发件人和收件人一样,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO,new InternetAddress("收件人邮箱"));
//邮件标题
message.setSubject("简单邮件");
message.setContent("<h1>测试发送!!!!</h1>","text/html;charset=utf-8");
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//关闭连接
ts.close();
}
}
//指明收件人,现在发件人和收件人一样,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO,new InternetAddress("收件人邮箱"));
//邮件标题
message.setSubject("简单邮件");
message.setContent("<h1>测试发送!!!!</h1>","text/html;charset=utf-8");
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//关闭连接
ts.close();
}
}