准备导包
原理
package com.zou;
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 MailDome01 {
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");//需要验证用户名密码
//关于qq邮箱还要设置ssl加密,加上以下代码
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("2246781190@qq.com", "gyxyarwlgecae");
}
});
//开启session的debug模式,这样就可以查看到程序发送email的运行状态
session.setDebug(true);
//通过session得到transport对象
Transport transport = session.getTransport();
//使用邮箱的用户名和授权码连上邮件服务器
transport.connect("smtp.qq.com","2246781190@qq.com","gyxytarwlgecae");
//创建邮件对象
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress("2246781190@qq.com"));
message.setRecipient(Message.RecipientType.TO,new InternetAddress("2246781190@qq.com"));//收件人可以是自己,可以是多个
message.setSubject("我是idea信息");//邮件主题
MimeBodyPart image=new MimeBodyPart();//发送图片对象
DataHandler dh = new DataHandler(new FileDataSource("E:\\mail-java\\src\\熊猫.png"));//图片位置
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();//保存
//发送邮件
transport.sendMessage(message,message.getAllRecipients());
//关闭连接
transport.close();
}}