使用Java应用程序发送 E-mail 十分简单,但是首先你应该在你的机器上安装 JavaMail API 和Java Activation Framework (JAF) 。
- 您可以从 Java 网站下载最新版本的 JavaMail,打开网页右侧有个 Downloads 链接,点击它下载。
- 您可以从 Java 网站下载最新版本的 JAF(版本 1.1.1)。
你也可以使用本站提供的下载链接:
pom.xml添加如下依赖
<!-- 邮件依赖-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
public class SendEmail {
public static void main(String [] args)
{
// 收件人电子邮箱
String to = "qingwuxxx@126.com";
// 发件人电子邮箱
String from = "lyl@xxx.com";
// 指定发送邮件的主机为 localhost
String host = "smtp.qq.com";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
// properties.setProperty("mail.user", "xxx");
// properties.setProperty("mail.password", "xxx");
// 获取默认session对象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("liyongli@sunlands.com", "lyl!1116"); //发件人邮件用户名、密码
}
});
try{
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// Set From: 头部头字段
message.setFrom(new InternetAddress(from));
// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
//抄送CC 密送BCC
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(from));
//一次添加多个收件人
// message.addRecipients(Message.RecipientType.TO,to+","+from);
// Set Subject: 头部头字段
message.setSubject("This is the Subject Line!");
// 设置消息体
message.setText("This is actual message -test Bcc");
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (AddressException e) {
e.printStackTrace();
} catch (javax.mail.MessagingException e) {
e.printStackTrace();
}
}
}