java mail实现Email的发送,完整代码

时间:2021-05-10 16:30:04

java mail实现Email的发送,完整代码

1、对应用程序配置邮件会话

首先, 导入jar

    <dependencies>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.2</version>
</dependency>
</dependencies>

  javax.mail.Session保存邮件系统的配置属性和提供用户验证的信息,发送email首先要获取session对象。

    1. Session.getInstance(java.util.Properties)获取非共享的session对象
    2. Session.getDefaultInstance(java.utilProperties)获取共享的session对象

  两者都必须建立Properties prop=new Properties()对象;

注意:  一般对单用户桌面应用程序使用共享Session对象。

  用SMTP协议发送Email时通常要设置mail.smtp.host(mail.protocol.host协议特定邮件服务器名)属性。

prop.put("mail.smtp.host","smtp.mailServer.com");

Session mailSession=Session.getInstance(prop);

注意:  在真正使用创建的过程中,往往会让我们验证密码,这是我们要写一个密码验证类。javax.mail.Authenticator是一个抽象类,我们要写MyAuthenticator的密码验证类,该类继承Authenticator实现:

 protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(String userName, String password);
}

这时我们创建Session对象:

Session mailSession=Session.getInstance(prop,new MyAuthenticator(userName,Password));

prop.put("mail.smtp.auth","true"); //并且要设置使用验证:
prop.put("mail.smtp.starttls.enable","true"); //使用 STARTTLS安全连接:

2、配置邮件会话之后,要编写消息

  要编写消息就要生成javax.mail.Message子类的实例或对Internet邮件使用javax.mail.interet.MimeMessage类。

(1)建立MimeMessage对象

  MimeMessage扩展抽象的Message类,构造MimeMessage对象:

MimeMessage message=new MimeMessage(mailSession);

(2)消息发送者、日期、主题

message.setFrom(Address theSender);
message.setSentDate(java.util.Date theDate);
message.setSubject(String theSubject);

(3)设置消息的接受者与发送者(寻址接收)

  setRecipient(Message.RecipientType type , Address theAddress)、setRecipients(Message.RecipientType type , Address[] theAddress)、addRecipient(Message.RecipientType type , Address theAddress)、addRecipients(Message.RecipientType type,Address[] theAddress)方法都可以指定接受者类型,但是一般用后两个,这样可以避免意外的替换或者覆盖接受者名单。定义接受者类型:

Message.RecipientType.TO://消息接受者
Message.RecipientType.CC://消息抄送者
Message.RecipientType.BCC://匿名抄送接收者(其他接受者看不到这个接受者的姓名和地址)

(4)设置消息内容

  JavaMail基于JavaBean Activation FrameWork(JAF),JAF可以构造文本消息也可以支持附件。

  设置消息内容时,要提供消息的内容类型-----即方法签名:

MimeMessage.setContent(Object theContent,String type);

也可以不用显式的制定消息的内容类型:MimeMessage.setText(String theText);

注意:建立地址javax.mail.InternetAddress toAddress=new InternetAddress(String address);

3、发送Email,这里以文本消息为例

  javax.mail.Transport类来发送消息。这时Transport对象与相应传输协议通信,这里是SMTP协议。

Transport transport = mailSession.getTransport("smtp");//定义发送协议
transport.connect(smtpHost,"chaofeng19861126", fromUserPassword);//登录邮箱
transport.send(message, message.getRecipients(RecipientType.TO));//发送邮件

下面是一个完整的代码:--------->>SendMail.java

package com.tools;

import java.util.Calendar;
import java.util.Properties; import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; public class SendMail {
@SuppressWarnings("static-access")
public static void sendMessage(String smtpHost, String from,
String fromUserPassword, String to, String subject,
String messageText, String messageType) throws MessagingException {
// 第一步:配置javax.mail.Session对象
System.out.println("为" + smtpHost + "配置mail session对象"); Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.starttls.enable", "true");// 使用 STARTTLS安全连接
// props.put("mail.smtp.port", "25"); //google使用465或587端口
props.put("mail.smtp.auth", "true"); // 使用验证
// props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props, new MyAuthenticator(
from, fromUserPassword)); // 第二步:编写消息
System.out.println("编写消息from——to:" + from + "——" + to); InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to); MimeMessage message = new MimeMessage(mailSession); message.setFrom(fromAddress);
message.addRecipient(RecipientType.TO, toAddress); message.setSentDate(Calendar.getInstance().getTime());
message.setSubject(subject);
message.setContent(messageText, messageType); // 第三步:发送消息
Transport transport = mailSession.getTransport("smtp");
transport.connect(smtpHost, "chaofeng19861126", fromUserPassword);
transport.send(message, message.getRecipients(RecipientType.TO));
System.out.println("message yes");
} public static void main(String[] args) {
try {
SendMail.sendMessage("smtp.gmail.com", "karemjohn@gmail.com",
"************", "karemjohn@gmail.com", "nihao",
"---------------wrwe-----------",
"text/html;charset=gb2312");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} class MyAuthenticator extends Authenticator {
String userName = "";
String password = ""; public MyAuthenticator() { } public MyAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
} protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}

前边发过一个比较简单,这个就比较适用了,也方便以后使用:

第一个文件:------>>MailSenderInfo.java

功能:封装了发送邮件的基本信息

package com.util.mail;
/**
* 发送邮件需要使用的基本信息
*/
import java.util.Properties;
public class MailSenderInfo { // 发送邮件的服务器的IP和端口
private String mailServerHost;
private String mailServerPort = "25"; // 邮件发送者的地址
private String fromAddress; // 邮件接收者的地址
private String toAddress; // 登陆邮件发送服务器的用户名和密码
private String userName;
private String password; // 是否需要身份验证
private boolean validate = false; // 邮件主题
private String subject; // 邮件的文本内容
private String content; // 邮件附件的文件名
private String[] attachFileNames;
/**
* 获得邮件会话属性
*/
public Properties getProperties(){
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] fileNames) {
this.attachFileNames = fileNames;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String textContent) {
this.content = textContent;
}
}

第二个文件:----------->>SimpleMailSender.java

功能:一个只发送文本的发送器

package com.util.mail;  

import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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 SimpleMailSender {
/**
* 以文本格式发送邮件
* @param mailInfo 待发送的邮件的信息
*/
public boolean sendTextMail(MailSenderInfo mailInfo) {
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// 设置邮件消息的主要内容
String mailContent = mailInfo.getContent();
mailMessage.setText(mailContent);
// 发送邮件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
} /**
* 以HTML格式发送邮件
* @param mailInfo 待发送的邮件信息
*/
public static boolean sendHtmlMail(MailSenderInfo mailInfo){
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
//如果需要身份认证,则创建一个密码验证器
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO属性表示接收者的类型为TO
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
// 发送邮件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
}

第三个文件:——————>>MyAuthenticator.java

功能:密码验证器

package com.util.mail;  

import javax.mail.*;
/**
密码验证器
*/
public class MyAuthenticator extends Authenticator{
String userName=null;
String password=null; public MyAuthenticator(){
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}

程序入口,主函数:

public static void main(String[] args){
//这个类主要是设置邮件
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setMailServerHost("smtp.163.com");
mailInfo.setMailServerPort("25");
mailInfo.setValidate(true);
mailInfo.setUserName("chaofeng19861126@163.com");
mailInfo.setPassword("********");//您的邮箱密码
mailInfo.setFromAddress("chaofeng19861126@163.com");
mailInfo.setToAddress("karemjohn@gmail.com");
mailInfo.setSubject("设置邮箱标题");
mailInfo.setContent("设置邮箱内容");
//这个类主要来发送邮件
SimpleMailSender sms = new SimpleMailSender();
sms.sendTextMail(mailInfo);//发送文体格式
sms.sendHtmlMail(mailInfo);//发送html格式
}

出自:  http://blog.csdn.net/karem/article/details/4646071