JavaMail郵件發送
1、導入mail.jar,mail-api.jar。
2、JavaMail工具類代碼:
public class JavaMail {
/**
* Message對象将存儲我們實際發送的電子郵件資訊,
* Message對象被作為一個MimeMessage對象來建立并且需要知道應當選擇哪一個JavaMail session。
*/
private MimeMessage message;
/**
* Session類代表JavaMail中的一個郵件會話。
* 每一個基于JavaMail的應用程式至少有一個Session(可以有任意多的Session)。
*
* JavaMail需要Properties來建立一個session對象。
* 尋找"mail.smtp.host" 屬性值就是發送郵件的主機
* 尋找"mail.smtp.auth" 身份驗證,目前免費郵件伺服器都需要這一項
*/
private Session session;
/***
* 郵件是既可以被發送也可以被接受。JavaMail使用了兩個不同的類來完成這兩個功能:Transport 和 Store。
* Transport 是用來發送資訊的,而Store用來收信。這裡隻需要用到Transport對象。
*/
private Transport transport;
private String mailHost="ismtp.beyondsoft.com";//伺服器位址
private int mailport=465;//端口
private String sender_username="[email protected]";//使用者名
private String sender_password="xiebin0220141222";//密碼
private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";//指定ssl的工廠
private Properties properties = new Properties();
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
/**
* 初始化方法
* @throws IOException
*/
public JavaMail(boolean debug) throws IOException {
InputStream in = JavaMail.class.getClassLoader().getResourceAsStream("empcare.properties");
properties.load(in);
this.mailHost = properties.getProperty("mail.smtp.host");
this.mailport = Integer.parseInt(properties.getProperty("mail.smtp.port"));
this.sender_username = properties.getProperty("mail.send.username");
this.sender_password = properties.getProperty("mail.send.password");
this.SSL_FACTORY = properties.getProperty("mail.smtp.socketFactory.class");
Properties props = new Properties();
// 指定SMTP伺服器
props.put("mail.smtp.host", this.mailHost);
props.put("mail.smtp.port", String.valueOf(this.mailport));
props.put("mail.smtp.starttls.enable","true");
// 指定是否需要SMTP驗證
props.put("mail.smtp.auth", "true");
// If you need to authenticate
// Use the following if you need SSL
//添加安全權限
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
props.put("mail.smtp.socketFactory.port", String.valueOf(this.mailport)); // 指定SMTP ssl伺服器
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.ssl.protocols", properties.getProperty("mail.smtp.ssl.protocols"));
session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sender_username, sender_password);
}});
//session = Session.getDefaultInstance(properties);
session.setDebug(debug);//開啟後有調試資訊
message = new MimeMessage(session);
}
/**
* 發送郵件
*
* @param subject
* 郵件主題
* @param sendHtml
* 郵件内容
* @param receiveUser
* 收件人位址
*/
@SuppressWarnings("static-access")
public boolean doSendHtmlEmail(String subject, String sendHtml,String receiveUser) {
boolean res=true;
try {
// 發件人
//InternetAddress from = new InternetAddress(sender_username);
// 下面這個是設定發送人的Nick name
InternetAddress from = new InternetAddress(" <"+sender_username+">");
message.setFrom(from);
// 收件人
InternetAddress to = new InternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO, to);//還可以有CC、BCC
// 郵件主題
message.setSubject(subject);
String content = sendHtml.toString();
// 郵件内容,也可以使純文字"text/plain"
message.setContent(content,"text/html;charset=UTF-8");
// 儲存郵件
message.saveChanges();
//第一種方式
//transport = session.getTransport("smtp");
// smtp驗證,就是你用來發郵件的郵箱使用者名密碼
//transport.connect(mailHost,mailport,sender_username, sender_password);
// 發送
//transport.sendMessage(message, message.getAllRecipients());
//第二種方式
transport.send(message);
System.out.println("send success!");
} catch (Exception e) {
e.printStackTrace();
res=false;
}finally {
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
return res;
}
/**
* 發送多人郵件
*
* @param subject
* 郵件主題
* @param sendHtml
* 郵件内容
* @param receiveUsers
* 收件人位址
*/
public boolean doSendHtmlEmail(String subject, String sendHtml,String [] receiveUsers) {
boolean res=true;
try {
// 發件人
//InternetAddress from = new InternetAddress(sender_username);
// 下面這個是設定發送人的Nick name
InternetAddress from = new InternetAddress(" <"+sender_username+">");
message.setFrom(from);
// 收件人
Address[] address =new InternetAddress[receiveUsers.length];
for (int i = 0; i < receiveUsers.length; i++) {
address[i]=new InternetAddress(receiveUsers[i]);
}
message.setRecipients(Message.RecipientType.TO, address);//還可以有CC、BCC
// 郵件主題
message.setSubject(subject);
String content = sendHtml.toString();
// 郵件内容,也可以使純文字"text/plain"
message.setContent(content, "text/html;charset=UTF-8");
// 儲存郵件
message.saveChanges();
transport = session.getTransport("smtp");
// smtp驗證,就是你用來發郵件的郵箱使用者名密碼
transport.connect(mailHost,mailport,sender_username, sender_password);
// 發送
transport.sendMessage(message, message.getAllRecipients());
System.out.println("send success!");
} catch (Exception e) {
e.printStackTrace();
res=false;
}finally {
if(transport!=null){
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
return res;
}
public static void main(String[] args) throws MessagingException, IOException {
JavaMail se = new JavaMail(true);
String [] test={"[email protected]","[email protected]"};
se.doSendHtmlEmail("主題", "<h1>内容</h1>", "[email protected]");
}
}
3、當然還需要配置下配置檔案
mail.smtp.host=
mail.smtp.port=
mail.send.username=
mail.send.password=
mail.smtp.socketFactory.port=
mail.smtp.socketFactory.class=
mail.smtp.ssl.protocols=