package com.java.mail;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class Mail2 {
public static void main(String[] args) {
//得到Sesion
Properties properties = new Properties();
properties.setProperty("mail.host", "smtp.163.com");
properties.setProperty("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("邮箱名","邮箱密码");
}
};
Session session = Session.getInstance(properties, authenticator);
//创建MimeMessage
MimeMessage message = new MimeMessage(session);
try {
//设置发件人
message.setFrom(new InternetAddress("发件人邮箱"));
//设置收件人
message.setRecipients(RecipientType.TO, "收件人邮箱");
//设置文件的内容
message.setSubject("这是一封来自itachi的邮件");
/*
* 当发送包含附件的邮件时,邮件体就为多部件形式
* 1、创建一个多部件的部件内容!MimeMultipart
* MimeMultipart就是一个集合,用来装载多个主体部件
* 2、我们需要创建两个主体部件,一个是文本内容的,另一个是附件的
* 主体部件叫MimeBodyPart
* 3、把MimeMultipart设置给MimeMessage的内容
*/
//创建多部件内容
MimeMultipart list = new MimeMultipart();
//创建MimeBodyPart
MimeBodyPart part = new MimeBodyPart();
//设置主体部件的内容
part.setContent("这是一封包含附件的邮件", "text/html;charset=utf-8");
//把主体部件添加到集合中
list.addBodyPart(part);
//创建MimeBodyPart
MimeBodyPart part_ = new MimeBodyPart();
//设置附件的内容
part_.attachFile(new File("F:/f/莫圣急.jpg"));
//设置显示的文件名称,其中encodeText用来处理中文乱码问题
part_.setFileName(MimeUtility.encodeText("疾雷娜.jpg"));
list.addBodyPart(part_);
//把它设置给邮件作为邮件内容
message.setContent(list);
//发
Transport.send(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}