使用JavaMail可以很方便的发送html格式的邮件,只需要将content-type设置为"text/html"即可。要在邮件中包含图片简单办法是使用image标签,src指向服务器上图片的位置。但是有些邮件客户端会把是否包含有服务器端图片作为垃圾邮件的判断机制。我们可以将图片内嵌到邮件中,然后用cid加content-id引用内嵌的图片。
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.Properties;
class SimpleMail2 {
public static void main(String[] args) throws Exception{
System.out.println("Sending mail...");
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "");
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML mail with images");
message.setFrom(new InternetAddress("[emailprotected]"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("[emailprotected]"));
//
// This HTML mail have to 2 part, the BODY and the embedded image
//
MimeMultipart multipart = new MimeMultipart("related");
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "
Hello
";messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource
("C:\\images\\jht.gif");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","");
// add it
multipart.addBodyPart(messageBodyPart);
// put everything together
message.setContent(multipart);
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}