1.实现邮件发送功能的前言
了解协议
SMTP协议:发送邮件的协议,我们通常把处理用户SMTP邮件发送请求的服务器称之为SMTP服务器
POP3协议:接受邮件,我们通常把处理用户pop3请求(邮件接收请求)的服务器称之为pop3服务器
这些邮件服务器就好像生活中的邮局,它主要负责接受用户投递过来的邮件,并把邮件投递到邮件接收者的邮箱中。
SMTP服务器:新浪邮箱smtp.163.com,qq邮箱smtp.qq.com
邮件发送的实现过程
- 创建包含邮件服务器的网络连接信息的Session对象
- 创建含有内容的Message对象
- 创建Transport对象,连接服务器
- 发送Message
- 关闭连接
市场上邮件类型太多,有新浪邮件,qq邮件,阿里邮件等等,今天我们就举例用Java实现我们最常用的qq邮件发送功能。
2.Java实现qq邮件发送功能
实现条件
首先我们获取QQ邮箱中对应的权限
打开QQ邮箱
打开账户
找到这个,然后点开启,会出现一串授权码 数字,记住这一串数字。
然后需要准备两个jar包,分别是
- mail.jar
- activation.jar
实现邮件发送功能,需要先导入这两个包
发送纯文本邮件
建Java类,编写代码
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class SendMail {
public static void main(String[] args) throws GeneralSecurityException, MessagingException {
Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com");// 设置QQ邮件服务器
properties.setProperty("mail.transport.protocol","smtp");// 邮件发送协议
properties.setProperty("mail.smtp.auth","true");// 需要验证用户名密码
// 关于QQ邮箱,还要设置SSL加密,加上以下代码即可
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",sf);
//1.创建一个session会话对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("1484501121@qq.com", "urhjhaphvjbjiafe");
}
});
session.setDebug(true);
//2.获取连接对象,通过session对象获得transport,需要铺货异常
Transport tp = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
tp.connect("smtp.qq.com","1484501121@qq.com","urhjhaphvjbjiafe");
//4.创建邮件
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//指明邮件发送人
message.setFrom(new InternetAddress("1484501121@qq.com"));
//指明邮件的收件人
message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("1484501121@qq.com")});
//邮件的标题
message.setSubject("只包含文本的简单邮件");
//邮件的文本内容
message.setContent("你好啊","text/html;charset=utf-8");
//发送邮件
tp.sendMessage(message,message.getAllRecipients());
tp.close();
}
}
运行后,qq马上就收到了自己给自己发的邮件,如图
发送内嵌图片加文本的邮件
建Java类,编写代码
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;
//发送包含图片的邮件
public class SendImageMail {
public static void main(String[] args) throws GeneralSecurityException, MessagingException {
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发送邮件五个步骤
//1.创建定义整个应用程序所需的环境信息的Session对象
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("1484501121@qq.com","mwoiyixrognohdid");
}
});
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","1484501121@qq.com","mwoiyixrognohdid");
//4.创建邮件
//创建邮件
MimeMessage message = new MimeMessage(session);
//设置邮件的基本信息
//发件人
message.setFrom(new InternetAddress("1484501121@qq.com"));
//收件人
message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("1484501121@qq.com")});
//邮件标题
message.setSubject("带图片的邮件");
//准备邮件数据
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource("src/resources/timg.jpg");
DataHandler dh = new DataHandler(fileDataSource);
image.setDataHandler(dh);
image.setContentID("timg.jpg");
//准备正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片<img src='cid:timg.jpg'>的邮件", "text/html;charset=UTF-8");
//描述数据关系
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");
//设置到消息中,保存修改
message.setContent(mm);
message.saveChanges();
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
ts.close();
}
}
运行后,qq马上就收到了自己给自己发的邮件,如图:
发送带图片和附件的复杂邮件
生活中,我们经常会给好友发送带有附件的邮件,下面就来实现这一功能
建另一个Java类,编写好代码
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class SendFileMail {
public static void main(String[] args) throws MessagingException, GeneralSecurityException {
//创建一个配置文件保存并读取信息
Properties properties = new Properties();
//设置qq邮件服务器
properties.setProperty("mail.host","smtp.qq.com");
//设置发送的协议
properties.setProperty("mail.transport.protocol","smtp");
//设置用户是否需要验证
properties.setProperty("mail.smtp.auth", "true");
//=================================只有QQ存在的一个特性,需要建立一个安全的链接
// 关于QQ邮箱,还要设置SSL加密,加上以下代码即可
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//=================================准备工作完毕
//1.创建一个session会话对象;
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("1484501121@qq.com", "mwoiyixrognohdid");
}
});
//可以通过session开启Dubug模式,查看所有的过程
session.setDebug(true);
//2.获取连接对象,通过session对象获得Transport,需要捕获或者抛出异常;
Transport tp = session.getTransport();
//3.连接服务器,需要抛出异常;
tp.connect("smtp.qq.com","1484501121@qq.com","mwoiyixrognohdid");
//4.连接上之后我们需要发送邮件;
MimeMessage mimeMessage = imageMail(session);
//5.发送邮件
tp.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
//6.关闭连接
tp.close();
}
public static MimeMessage imageMail(Session session) throws MessagingException {
//消息的固定信息
MimeMessage mimeMessage = new MimeMessage(session);
//邮件发送人
mimeMessage.setFrom(new InternetAddress("1484501121@qq.com"));
//邮件接收人,可以同时发送给很多人,我们这里只发给自己;
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("1484501121@qq.com"));
mimeMessage.setSubject("我也不知道是个什么东西就发给你了"); //邮件主题
/*
编写邮件内容
1.图片
2.附件
3.文本
*/
//图片
MimeBodyPart body1 = new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("src/resources/timg.jpg")));
body1.setContentID("timg.jpg"); //图片设置ID
//文本
MimeBodyPart body2 = new MimeBodyPart();
body2.setContent("请注意,我不是广告<img src='cid:timg.jpg'>","text/html;charset=utf-8");
//附件
MimeBodyPart body3 = new MimeBodyPart();
body3.setDataHandler(new DataHandler(new FileDataSource("src/resources/log4j.properties")));
body3.setFileName("log4j.properties"); //附件设置名字
MimeBodyPart body4 = new MimeBodyPart();
body4.setDataHandler(new DataHandler(new FileDataSource("src/resources/666.txt")));
body4.setFileName(""); //附件设置名字
//拼装邮件正文内容
MimeMultipart multipart1 = new MimeMultipart();
multipart1.addBodyPart(body1);
multipart1.addBodyPart(body2);
multipart1.setSubType("related"); //1.文本和图片内嵌成功!
//new MimeBodyPart().setContent(multipart1); //将拼装好的正文内容设置为主体
MimeBodyPart contentText = new MimeBodyPart();
contentText.setContent(multipart1);
//拼接附件
MimeMultipart allFile =new MimeMultipart();
allFile.addBodyPart(body3); //附件
allFile.addBodyPart(body4); //附件
allFile.addBodyPart(contentText);//正文
allFile.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed;
//放到Message消息中
mimeMessage.setContent(allFile);
mimeMessage.saveChanges();//保存修改
return mimeMessage;
}
}
运行后,就受到了邮件,如图:
邮件发送成功!!!