- package com.wangxin.test;
-
- import java.security.Security;
- import java.util.Date;
- import java.util.Properties;
-
- import javax.mail.Authenticator;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
-
- /**
- * javaMail的郵件工具類
- * @author wangXgnaw
- *
- */
- public class MailUtil {
-
- /**
- * 使用加密的方式,利用465端口進行傳輸郵件,開啟ssl
- * @param to 為收件人郵箱
- * @param message 發(fā)送的消息
- */
- public static void sendEmil(String to, String message) {
- try {
- Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
- final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
- //設(shè)置郵件會話參數(shù)
- Properties props = new Properties();
- //郵箱的發(fā)送服務(wù)器地址
- props.setProperty("mail.smtp.host", "smtp.sina.com");
- props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
- props.setProperty("mail.smtp.socketFactory.fallback", "false");
- //郵箱發(fā)送服務(wù)器端口,這里設(shè)置為465端口
- props.setProperty("mail.smtp.port", "465");
- props.setProperty("mail.smtp.socketFactory.port", "465");
- props.put("mail.smtp.auth", "true");
- final String username = "發(fā)送者郵箱用戶名";
- final String password = "發(fā)送者郵箱密碼或者郵箱授權(quán)碼";
- //獲取到郵箱會話,利用匿名內(nèi)部類的方式,將發(fā)送者郵箱用戶名和密碼授權(quán)給jvm
- Session session = Session.getDefaultInstance(props, new Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username, password);
- }
- });
- //通過會話,得到一個郵件,用于發(fā)送
- Message msg = new MimeMessage(session);
- //設(shè)置發(fā)件人
- msg.setFrom(new InternetAddress("發(fā)件人郵箱"));
- //設(shè)置收件人,to為收件人,cc為抄送,bcc為密送
- msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
- msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
- msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
- msg.setSubject("郵件主題");
- //設(shè)置郵件消息
- msg.setText(message);
- //設(shè)置發(fā)送的日期
- msg.setSentDate(new Date());
-
- //調(diào)用Transport的send方法去發(fā)送郵件
- Transport.send(msg);
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
-