参考书籍《张孝详java邮件开发详解》
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Service;
import javax.mail.Session;
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.Transport;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class HtmlMessageSender {
String protocol = "smtp";
String from = "xxxxxxxxxxx@sina.com";
String to = "xxxxxxxxxxxx@qq.com";
String subject = "HTML测试";
String body = "<a href=www.baidu.com><h4>欢迎大家订阅此邮件</h4></a>" + "<img src=\"cid:test_img\">";
public static void main(String[] args) throws Exception {
String server = "smtp.sina.com"; //新浪smtp接受服务器
String user = "xxxxxxxxxx"; //不需要写@sina.com
String pass = "用授权码替代密码";
HtmlMessageSender sender = new HtmlMessageSender();
Session session = sender.createSession();
MimeMessage message = sender.createMessage(session);
//获得Transport对象,并连接邮件服务器发送邮件
Transport transport = session.getTransport(); //导入包时不要导错了javax.mail.Transport;
transport.connect(server, user, pass);
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
public Session createSession() {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", protocol);
/* 必须将mail.smtp.auth属性设置为true,SMTPTransport对象才会向SMTP
* 服务器提交用户认证信息,这个信息可以从JavaMail的javadocs文档
* 中的com.su.mail.smtp包的帮助页面内查看到
*/
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
return session;
}
public MimeMessage createMessage(Session session) throws Exception {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
MimeMultipart multipart = new MimeMultipart("related");
MimeBodyPart htmlBodyPart = new MimeBodyPart();
htmlBodyPart.setContent(body,"text/html;charset=gb2312");
multipart.addBodyPart(htmlBodyPart);
MimeBodyPart gifBodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("F:\\个人资料\\xxxx.jpg");
gifBodyPart.setDataHandler(new DataHandler(fds));
gifBodyPart.setContentID("test_img");
multipart.addBodyPart(gifBodyPart);
message.setContent(multipart);
message.saveChanges();
return message;
}
}