一、邮件简介
示例:创建一个邮件并写到磁盘
package mail;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMail2 {
public static void main(String args[]){
Session session = Session.getInstance(new Properties());
MimeMessage message = new MimeMessage(session);
try {
//设置邮件的基本信息
message.setFrom(new InternetAddress("xx@sina.com"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("xx@sina.com"));
message.setSubject("测试");
//邮件正文
MimeBodyPart text = new MimeBodyPart();
text.setContent("我就是我xxx","text/html;charset=UTF-8");
//创建邮件附件
MimeBodyPart attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("e:\\z_src\\images\\1.jpg"));
attach.setDataHandler(dh);
attach.setFileName(dh.getName());
//创建容器描述 数据关系
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(text);
mp.addBodyPart(attach);
mp.setSubType("mixed");
message.setContent(mp);
message.saveChanges();
message.writeTo( new FileOutputStream("e:\\1.eml"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例2:发送邮件
public class SendMail {
public static void main(String args[]){
Properties prop = new Properties();
prop.setProperty("mail.smtp.host", "smtp.sohu.com");
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
try {
//1、创建Session
Session session = Session.getInstance(prop);
session.setDebug(true);
//2、创建Transport
Transport ts = session.getTransport();
//3、创建邮件
Message message = makeMessage(session);
//连上邮件服务器
ts.connect("smtp.sohu.com", "username", "password");
//发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public static Message makeMessage(Session session) throws AddressException, MessagingException{
MimeMessage message = new MimeMessage(session);
//设置邮件的基本信息
message.setFrom(new InternetAddress(""));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(""));
message.setSubject("test");
message.setContent("aaa", "text/html");
return message;
}
}
转自:传智播客