关于使用JavaMail发送邮件

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.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 JavaMailTest {
public void sendMail() throws MessagingException{
String html="<!DOCTYPE HTML><html lang=\"zh-CN\" dir=\"ltr\"><head><meta charset=\"UTF-8\"/>"
+"<title></title>
+"</style></head><body>
+"<img src=\"cid:图片id\" style=\"float:left;\">
+"</body></html>";

注意:html中的部分内容需要用\转义

//图片地址
String imageURL = "此处为图片所存储的路径(物理路径)";
//发件人邮箱
String sendMail = " ";
//发件邮箱密码
String sendMailPass = " ";
//收件人邮箱
String receiptMail = " ";

Properties proper = new Properties();
//设置发送给邮件服务器的信息
proper.put("mail.smtp.host","smtp.exmail.qq.com");
proper.put("mail.smtp.starttls.enable", "true");

//创建邮件session对象
Session mailSession = Session.getInstance(proper,null);
mailSession.setDebug(false);
//创建邮件对象
Message message = new MimeMessage(mailSession);
//创建邮件内容,设置邮件内容各部分关联关系
MimeMultipart mailContentBody = new MimeMultipart("related");
//设置html邮件部分
MimeBodyPart htmlBody = new MimeBodyPart();
htmlBody.setContent(html, "text/html;charset=utf-8");
//将html邮件部分体放入邮件内容
mailContentBody.addBodyPart(htmlBody);
//创建存放邮件图像的邮件部分
MimeBodyPart imageBody = new MimeBodyPart();
//设置图片数据源
FileDataSource file = new FileDataSource(imageURL);
imageBody.setDataHandler(new DataHandler(file));
//设置图片在邮件内容中的唯一id
imageBody.setContentID("图片id,可任意");
//将imageBody放入邮件内容当中
mailContentBody.addBodyPart(imageBody);

//设置发件人
message.setFrom(new InternetAddress(sendMail));
//设置收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiptMail));
//设置邮件主题
message.setSubject("测试javaMail");
//设置邮件正文
message.setContent(mailContentBody);
//设置发件事件
message.setSentDate(new Date());
//保存邮件信息
message.saveChanges();

//创建邮件发送对象
Transport tx = mailSession.getTransport("smtp");
//连接邮件服务器
tx.connect("smtp.exmail.qq.com", sendMail, sendMailPass);
//发送邮件
tx.sendMessage(message, message.getAllRecipients());
//关闭连接
tx.close();
}

public static void main(String[] args){
JavaMailTest mail = new JavaMailTest();
try {
mail.sendMail();
} catch (MessagingException e) {
e.printStackTrace();
}
}

}

说明:此邮件中由图片作为邮件背景,图片也可不由程序加入,如图片有网络地址(url)也可在图片src处直接使用url地址,但每次打开邮件

        都会加载图片。

posted on 2013-07-04 23:03  java疯子  阅读(258)  评论(0)    收藏  举报

导航