Mail sending
•
Java
Mail sending
1. Principle
Send mail: SMTP protocol
Receiving mail: POP3 protocol
Simple mail: plain text mail without attachments and pictures
Complex mail: with attachments and pictures
To send mail, you need agreement and support
2. Sending simple mail
package com.wang;
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();
//设置QQ邮件服务器
prop.setProperty("mail.host","smtp.qq.com");
//邮件发送协议
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对象
//QQ才有,其他邮箱不用!
Session session = Session.getDefaultInstance(prop,new Authenticator() {
@Override
public PasswordAuthentication getpasswordAuthentication() {
//发送人邮件的用户名,授权码
return new PasswordAuthentication("715180879@qq.com","授权码");
}
});
//开启Session的Debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上服务器
ts.connect("smtp.qq.com","715180879@qq.com","授权码");
//4.创建邮件:写邮件
//注意需要传递session
MimeMessage message = new MimeMessage(session);
//邮件的发件人
message.setFrom(new InternetAddress("715180879@qq.com"));
//指明邮件的 收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO,new InternetAddress("715180879@qq.com"));
//邮件的标题
message.setSubject("简单邮件");
//邮件的文本内容
message.setContent("Hello!","text/html;charset=UTF-8");
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接
ts.close();
}
}
3. Sending complex mail
package com.wang;
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.util.Properties;
//发送一封复杂的邮件
public class MailDemo02 {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
//设置QQ邮件服务器
prop.setProperty("mail.host",new InternetAddress("715180879@qq.com"));
//邮件的标题
message.setSubject("复杂邮件");
//=================================================
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
//图片需要经过数据处理 DataHandler:数据处理
DataHandler dh = new DataHandler((new FileDataSource("D:\\Java_Web\\功能扩展\\mail-java\\src\\resources\\pic.jpg")));
//在我们的body中放入这个处理的图片数据
image.setDataHandler(dh);
//给图片设置一个ID,我们在后面可以使用!
image.setContentID("pic.jpg");
//准备正文数据
MimeBodyPart text = new MimeBodyPart();
//cid ==> ContentID
text.setContent("这是一封邮件正文带图片<img src='cid:pic.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());
//6.关闭连接
ts.close();
}
}
4. Sending of user registration email
package com.wang.pojo;
import java.io.Serializable;
//顺手将其序列化
public class User implements Serializable {
private String name;
private String password;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getpassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User(String name,String password,String email) {
this.name = name;
this.password = password;
this.email = email;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
",password='" + password + '\'' +
",email='" + email + '\'' +
'}';
}
}
package com.wang.servlet;
import com.wang.pojo.User;
import com.wang.util.Sendmail;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {
//接受用户请求,封装成对象
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
// System.out.println(username);
// System.out.println(password);
// System.out.println(email);
User user = new User(username,password,email);
//用户注册成功之后,给用户发送一封邮件
//我们使用线程来专门发送邮件,防止出现耗时,和网站注册人数过多的情况
Sendmail sendmail = new Sendmail(user);
//启动线程:线程启动之后就会执行run方法来发送邮件
sendmail.start();
//注册用户
req.setAttribute("message","注册成功,我们已经发送了一封带了注册信息的电子邮件,请查收!如果网络不稳定,可能会过会儿才能收到!!");
req.getRequestDispatcher("info.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req,IOException {
doGet(req,resp);
}
}
package com.wang.util;
import com.sun.mail.util.MailSSLSocketFactory;
import com.wang.pojo.User;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
//网站3秒原则:用户体验
//多线程实现用户体验! (异步处理)
public class Sendmail extends Thread {
//用于给用户发送邮件的邮箱
private String from = "715180879@qq.com";
//邮箱的用户名
private String username = "715180879@qq.com";
//邮箱的密码
private String password = "授权码";
//发送邮件的服务器地址
private String host = "smtp.qq.com";
private User user;
public Sendmail(User user) {
this.user = user;
}
//丛谢run方法的实现,在run方法中发送邮件给指定的用户
@Override
public void run() {
try {
Properties prop = new Properties();
prop.setProperty("mail.host",host);
//邮件发送协议
prop.setProperty("mail.transport.protocol","smtp");
//需要验证用户名和密码
prop.setProperty("mail.smtp.auth","true");
//关于QQ邮箱,其他邮箱不需要
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
//使用JavaMail发送邮件的五个步骤
//1.创建定义整个应用所需的环境信息的Session对象
//QQ才有,其他邮箱不用!
Session session = Session.getDefaultInstance(prop,new Authenticator() {
@Override
public PasswordAuthentication getpasswordAuthentication() {
//发送人邮件的用户名,授权码
return new PasswordAuthentication(from,password);
}
});
//开启Session的Debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上服务器
ts.connect(host,username,password);
//4.创建邮件:写邮件
//注意需要传递session
MimeMessage message = new MimeMessage(session);
//邮件的发件人
message.setFrom(new InternetAddress(from));
//指明邮件的 收件人,现在收件人是从前端接收来的
message.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getEmail()));
//邮件的标题
message.setSubject("用户注册邮件");
String info = "恭喜注册成功,您的用户名: " + user.getName() + "您的密码: " + user.getpassword() + "请妥善保管,如有问题请联系网站客服!";
message.setContent(info,"text/html;charset=UTF-8");
message.saveChanges();
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接
ts.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码