发送包含HTML内容的电子邮件,遵循的步骤是:
message.setContent("<h1>This is actual message embedded in HTML tags</h1>", "text/html");
发送使用传输对象的消息;
以下示例:
使用163 smtp 邮箱服务器发送,运行程序前,确保163邮箱开启smtp服务;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* create by Intellij IDEA
* Author: Al-assad
* E-mail: [email protected]
* Github: <https://github.com/Al-assad>
* Date: 2017/7/23 16:15
* Description:
*/
public class SendEmail {
public static void main(String[] args){
//邮箱服务器参数
String to = "[email protected]"; //收件地址
String from = "[email protected]"; //发送地址
String username = "[email protected]"; //邮箱验证用户名,一般第三方的POP,smtp服务,用户名为发送邮箱地址
String password = "*************"; //邮箱验证授权码
String host = "smtp.163.com"; //发送邮箱服务器,如果是本机配置为邮箱服务器,使用"localhost"参数
//设置邮件服务器参数、服务器端口等参数
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
//props.put("mail.smtp.port","25"); 使用第三方的smtp服务器可以不用设置端口
//设置Session对象,同时配置验证方法
Session session = Session.getInstance(props,new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
});
try{
//创建Message对象,并设置相关参数
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
//设置发送信息主题.信息正文
message.setSubject("Hello");
message.setContent("<h1>Hello</h1>" +
"<p>This is test HTML email using JavaMail</p>" +
"<a href=\"<https://www.baidu.com>\">Test anchor tab</a>","text/html");
//发送信息
Transport.send(message);
System.out.println("Email Sent!");
}catch(MessagingException e){
e.printStackTrace();
}
}
}
一般在工程中,会将HTML文本储存在一个html文件中,在 JavaMail 要发送送HTML文本时,再读取该html文件的文本使用;
要发送电子邮件,其中包含一个内嵌的图像,遵循的步骤是: