1. 导入包
<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>
2. 简单邮件发送
package com.thhh;
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");
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
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() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("XXXX@qq.com", "授权码");
}
});
session.setDebug(true);
Transport ts = session.getTransport();
ts.connect("smtp.qq.com", "XXXX@qq.com", "授权码");
MimeMessage 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("<h2 style='color:red'>你好啊!</h2>", "text/html;charset=UTF-8");
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
}
3. 复杂邮件发送
3.1 发送带图片的邮件
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 MailDemo01 {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.qq.com");
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
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() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("XXXX@qq.com", "授权码");
}
});
session.setDebug(true);
Transport ts = session.getTransport();
ts.connect("smtp.qq.com", "XXXX@qq.com", "授权码");
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("XXXX@qq.com"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("XXXX@qq.com"));
message.setSubject("简单邮件发送实现");
System.out.println("=============================复杂邮件的邮件内容设置==================================");
MimeBodyPart image = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("图片的绝对地址"));
image.setDataHandler(dh);
image.setContentID("bz.jpg");
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片<img src='cid:bz.jpg'>的邮件", "text/html;charset=UTF-8");
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");
message.setContent(mm);
message.saveChanges();
System.out.println("===============================================================");
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
}
3.2 发送包含附件的邮件
ystem.out.println("=============================复杂邮件的邮件内容设置==================================");
MimeBodyPart body1 = new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("图片的绝对地址")));
body1.setContentID("yhbxb.png");
MimeBodyPart body2 = new MimeBodyPart();
body2.setContent("请注意,我不是广告<img src='cid:yhbxb.png'>","text/html;charset=utf-8");
MimeBodyPart body3 = new MimeBodyPart();
body3.setDataHandler(new DataHandler(new FileDataSource("附件1的绝对地址")));
body3.setFileName("test.c");
MimeBodyPart body4 = new MimeBodyPart();
body4.setDataHandler(new DataHandler(new FileDataSource("附件2的绝对地址")));
body4.setFileName("test.txt");
MimeMultipart multipart1 = new MimeMultipart();
multipart1.addBodyPart(body1);
multipart1.addBodyPart(body2);
multipart1.setSubType("related");
MimeBodyPart contentText = new MimeBodyPart();
contentText.setContent(multipart1);
MimeMultipart allFile =new MimeMultipart();
allFile.addBodyPart(body3);
allFile.addBodyPart(body4);
allFile.addBodyPart(contentText);
allFile.setSubType("mixed");
message.setContent(allFile);
message.saveChanges();
System.out.println("===============================================================");
4. 网站注册发送邮件
4.1 工具类
package com.thhh.utils;
import com.sun.mail.util.MailSSLSocketFactory;
import com.thhh.pojo.User;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class Sendmail implements Runnable{
private String from = "XXXX@qq.com";
private String username = "XXXX@qq.com";
private String password = "授权码";
private User user;
public Sendmail(User user) {
this.user = user;
}
@Override
public void run() {
try {
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.qq.com");
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
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() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
Transport ts = session.getTransport();
ts.connect("smtp.qq.com", username, password);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
message.setSubject("欢迎注册thhh!");
message.setContent("<p><h2>恭喜注册成功!</h2></p>您的用户名为:<h4>"+user.getUsername()+"</h4>请妥善保管您的密码,如有问题请及时联系网站客服,再次欢迎您的加入!!", "text/html;charset=UTF-8");
ts.sendMessage(message, message.getAllRecipients());
ts.close();
} catch (MessagingException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
}
}
4.2 servlet
package com.yang.servlet.user;
import com.yang.pojo.User;
import com.yang.util.Constants;
import com.yang.util.SendMail;
import org.junit.Test;
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 LogonServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userCode = req.getParameter("userCode");
String userPassword = req.getParameter("userPassword");
User user = new User();
user.setUserCode(userCode);
user.setUserPassword(userPassword);
SendMail sendMail = new SendMail(user);
sendMail.start();
req.setAttribute(Constants.MESSAGE, "注册成功!我们已经向您的邮箱发送了邮件!");
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}