用javamail实现一个简单的邮件发送

时间:2022-05-25 19:01:03

导入两个jar包:activation.jar 和mail.jar

package cn.lfd.mail;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail {

/**
* 发送一条邮件
*/
public static void main(String[] args) throws Exception {
Properties pro = new Properties();
pro.setProperty("mail.host", "smtp.163.com");//主机名
pro.setProperty("mail.transport.protocol", "smtp");//协议号
pro.setProperty("mail.smtp.auth", "true");//是否验证登录

Session session = Session.getInstance(pro);
session.setDebug(true);//开发模式 打印出运行状态

//通过session得到Transport
Transport ts = session.getTransport();

//连接到服务器
ts.connect("smtp.163.com", "18770913843", "lfd88888888000");

//创建一条邮件
Message message = makeMessage(session);
ts.sendMessage(message, message.getAllRecipients());//把邮件发送出去
ts.close();//关闭连接
}

public static Message makeMessage(Session session) throws Exception, MessagingException {
MimeMessage message = new MimeMessage(session);
//准备邮件的基本信息
message.setFrom(new InternetAddress("18770913843@163.com"));//邮件发送人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("343468193@qq.com"));//邮件接收人
message.setSubject("美女图");//邮件主题


MimeBodyPart text = new MimeBodyPart();
text.setContent("----------<br><img src=\"cid:action\">","text/html;charset=utf-8");

//图片数据
MimeBodyPart image = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("src\\1.jpg"));
image.setDataHandler(dh);
image.setContentID("action");//和html链接的cid一致
//image.setFileName(MimeUtility.encodeText(dh.getName()));encodeText解决附件名中文乱码

MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(text);//把文字和图片这两个BodyPart放到MimeMultipart容器里
mp.addBodyPart(image);
mp.setSubType("related");//设置正文与图片的关系为related,若有附件,则附件与正文的关系为mixed

message.setContent(mp);//把mp这个容器加到MimeMessage
message.saveChanges();
return message;
}
}