java email 在阿里雲服務器發送郵件失敗的解決方法

昨天在弄騰訊企業郵發送郵件後臺,中間遇到了一個問題,就是在本地服務器可以正常發送郵件,但是佈署到阿里雲服務器就不行,於是在網上找了大半天解決方法,前後修修改改也花費了幾個小時,直到快下班了才弄出來,所以在這裏列出寫個博客,記錄一下自己的問題,順帶也貼上自己寫的工具類代碼,希望能幫助到更多開發者。

阿里雲服務器上不能發送郵件的問題:

1.騰訊企業郵箱不支持25端口,建議使用465端口(其他郵箱支持端口可以登錄賬號去設置裏查看);

2.使用465端口一定要開啓ssl協議;


下面是我修改後發送郵件的工具類:

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/** 
 * @ClassName: EmailUtil 
 * @Description: 郵件工具類
 * @author ZL
 * @date 2018年5月14日 下午3:31:23 
 *  
 */
public class EmailUtil {  
	
	private static Logger LOG = Logger.getLogger(EmailUtil.class);
	
	// 郵件服務地址
    private static String host = "smtp.exmail.qq.com";  
    // 發送用戶
    private static String username = "****";  
    // 發送用戶密碼
    private static String password = "****";
    // 發送暱稱
    private static String nick = "**商城";  
    
 
  
    /** 
    * @Title: sendMail 
    * @Description: 發送郵件  (激活用戶使用)
    * @param to 收件人
    * @param activeCode 激活碼
    * @throws AddressException
    * @throws MessagingException
    * @throws UnsupportedEncodingException    設定文件 
    * @return boolean    返回類型 
     */
    public static boolean sendMail(String to,String activeCode) throws AddressException, MessagingException,  
            UnsupportedEncodingException {
        // 激活碼判斷  
        if (StringUtils.isEmpty(activeCode)) {  
        	LOG.debug("#href is empty.");
            return false;
        }  
        String body = getBodyContent(to,activeCode);
        // 創建Properties對象  
        Properties props = System.getProperties();  
        // 創建信件服務器  
        props.put("mail.smtp.host", host);  
        props.put("mail.smtp.port", "465"); 
        props.put("mail.transport.protocol", "smtp");  
        props.put("mail.smtp.auth", "true"); // 通過驗證  
        
//        MailSSLSocketFactory sf = null;
//		try {
//			sf = new MailSSLSocketFactory();
//		} catch (GeneralSecurityException e) {
//			LOG.debug("#create MailSSLSocketFactory has error.",e);
//		}  
//        sf.setTrustAllHosts(true);
        
        props.put("mail.smtp.ssl.enable", "true");  // 開啓ssl
//        props.put("mail.smtp.ssl.socketFactory", sf); 	// 信任此站點證書
        
        // 得到默認的對話對象  
        Session session = Session.getDefaultInstance(props, null);  
        // 創建一個消息,並初始化該消息的各項元素  
        MimeMessage msg = new MimeMessage(session);  
        nick = MimeUtility.encodeText(nick);
        msg.setFrom(new InternetAddress(nick + "<" + username + ">"));  
        // 創建收件人列表  
        if (to != null && to.trim().length() > 0) {  
            String[] arr = to.split(",");  
            int receiverCount = arr.length;  
            if (receiverCount > 0) {  
                InternetAddress[] address = new InternetAddress[receiverCount];  
                for (int i = 0; i < receiverCount; i++) {  
                    address[i] = new InternetAddress(arr[i]);  
                }  
                msg.addRecipients(Message.RecipientType.TO, address);  
//                msg.setSubject(subject);  
                msg.setContent(body,"text/html;charset=utf-8");  
                // 設置信件頭的發送日期  
                msg.setSentDate(new Date());  
                msg.saveChanges();  
                // 發送信件  
                Transport transport = session.getTransport("smtp");  
                transport.connect(host, username, password);  
                transport.sendMessage(msg,  
                        msg.getRecipients(Message.RecipientType.TO));  
                transport.close();
                return true;  
            } else {  
            	LOG.debug("None receiver!");  
                return false;  
            }  
        } else {  
        	LOG.debug("None receiver!");  
            return false;  
        }  
    }

    /**
    * @Title: getBodyContent 
    * @Description: 獲取郵件正文內容
    * @param to
    * @param href
    * @return String    返回類型 
     */
    private static String getBodyContent(String to, String activeCode){
//    	String addr = SessionUtil.getRequest().getLocalAddr();
    	String addrName = SessionUtil.getRequest().getServerName();
    	String url = "";
    	if(addrName.equals("localhost")){
			url = SessionUtil.getRequest().getScheme() +"://" + getIp()+ ":" +SessionUtil.getRequest().getServerPort();
		}else{
			url = SessionUtil.getRequest().getScheme() +"://" + addrName + ":" +SessionUtil.getRequest().getServerPort();
		}
    	// 激活碼鏈接地址
    	url = url+"/****/****.action?code="+activeCode;
        LOG.debug("active url -> "+url);
    	StringBuilder body = new StringBuilder();
    	body.append("<p style='padding-bottom:20px;'>親愛的 <strong><a href='mailto:"+to+"' target='_blank'>"+to+"</a></strong>:</p>")
    			.append("<p style='background:#f7f7f7; padding:10px 20px;line-height:36px;'>")
    				.append("請點擊以下鏈接激活用戶:<br><a href='"+url+"' >"+url+"</a><br>")
    					.append("<span style='font-size:12px; color:#999;'>如果以上鍊接無法點擊,請將它複製到您的瀏覽器(如IE)地址欄中進入訪問。</span></p>")
    						.append("<p style='border-top:1px solid #ddd;color:#999;font-size:12px;padding-top:10px;'>這是一封系統自動發出的郵件,請勿回覆。</p>");
    	return body.toString();
    }
    /**
    * @Title: getIp 
    * @Description: 獲取電腦IP地址 
    * @param @return    設定文件 
    * @return String    返回類型 
    * @throws
     */
    public static String getIp(){
    	InetAddress addr = null;
		try {
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
        String ip=addr.getHostAddress().toString(); //獲取本機ip  
        return ip;
    }
    public static void main(String[] args) {
			System.out.println(getIp());
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章