邮件发送
2.jar包的支持
activation-1.1.1.jar
mail-1.4.7.jar
3.授权码的获取
4.简易文本邮件发送的实现
由上图我们可以确定几个必须步骤
1.创建session对象
2.创建Transport对象
3.使用邮箱的用户名和授权码连上邮件服务器
4.创建一个Message对象(需要传递session)
- message需要指明发件人、收件人以及文件内容
5.发送邮件
6.关闭连接
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 MailDemo01 {public static void main(String[] args) throws Exception {Properties prop=new Properties();prop.setProperty("mail.host","smtp.qq.com");///设置QQ邮件服务器prop.setProperty("mail.transport.protocol","smtp");///邮件发送协议prop.setProperty("mail.smtp.auth","true");//需要验证用户密码//QQ邮箱需要设置SSL加密MailSSLSocketFactory sf=new MailSSLSocketFactory();sf.setTrustAllHosts(true);prop.put("mail.smtp.ssl.enable","true");prop.put("mail.smtp.ssl.socketFactory",sf);//使用javaMail发送邮件的5个步骤//1.创建定义整个应用程序所需要的环境信息的session对象Session session=Session.getDefaultInstance(prop, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication("XXXX@qq.com","授权码");}});//开启session的debug模式,这样可以查看到程序发送Email的运行状态session.setDebug(true);//2.通过session得到transport对象Transport ts=session.getTransport();//3.使用邮箱的用户名和授权码连上邮件服务器ts.connect("smtp.qq.com","XXXX@qq.com","授权码");//4.创建邮件:写文件//注意需要传递sessionMimeMessage message=new MimeMessage(session);//指明邮件的发件人message.setFrom(new InternetAddress("XXXX@qq.com"));//指明邮件的收件人message.setRecipient(Message.RecipientType.TO,new InternetAddress("XXXX@qq.com"));//邮件标题message.setSubject("发送的标题");//邮件的文本内容message.setContent("内容","text/html;charset=UTF-8");//5.发送邮件ts.sendMessage(message,message.getAllRecipients());//6.关闭连接ts.close();}
}