Java mail实现HTML邮件的发送

1、前言

在现实生活中,我们经常会需要邮件的发送。手动发送已经成为一种耗时又费力的工作,那么如何更高效的利用代码来进行动态的发送呢?可能你又会问,代码编写的文本无法实现一些样式,不美观排版不好。所以,这篇文章主要介绍的就是采用Java Mail实现HTML email的发送。

2、实现

此方式比较简单,只需要一个main类即可。
Java代码:

package com.nicole;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.text.MessageFormat;
import java.util.ArrayList;
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;

import org.apache.commons.lang3.time.DateFormatUtils;

import com.sun.mail.util.MailSSLSocketFactory;

public class SendEmailTest {
	public static void main(String[] args) throws MessagingException, GeneralSecurityException, IOException {
		 MailSSLSocketFactory sf = new MailSSLSocketFactory();
	        sf.setTrustAllHosts( true );
	        Properties props = new Properties();
	        props.setProperty( "mail.transport.protocol", "SMTP" );
	        props.setProperty( "mail.host", "smtp.163.com" );
	        props.setProperty( "mail.smtp.auth", "true" );
	        props.setProperty( "mail.smtp.ssl.enable", "true" );
	        props.put( "mail.smtp.ssl.socketFactory",sf );
	 
	        Authenticator auth = new Authenticator() {
	            public PasswordAuthentication getPasswordAuthentication() {
	                return new PasswordAuthentication( "username", "password" ); //设置163邮箱的用户和登录授权码
	 
	            }
	        };
	        Session session = Session.getInstance( props, auth );
	        session.setDebug( true );
	        Message message = new MimeMessage( session );
	        message.setFrom( new InternetAddress( "[email protected]" ) ); // 设置发送者
	        message.setRecipient( MimeMessage.RecipientType.TO, new InternetAddress( "[email protected]" )); // 设置发送方式与接收者
	        String status = "New";
	        String msgId = "xwyMX";
	        message.setSubject("Notification to One – "+status+"("+msgId+")");
	        ArrayList<String[]> custlist = new ArrayList<String[]>();
            String[] cust1 = {"00000001", "SHANGSHA, FUTIAN DISTRICT, SHENZHEN","000000001BB"};
            String[] cust2 = {"00000002", "YUEHAI, NANSHANG DISTRICT, SHENZHEN","000000002BB"};
            String[] cust3 = {"00000003", "SHANGSHA, FUTIAN DISTRICT, SHENZHEN","000000003BB"};
		    custlist.add(cust1);
		    custlist.add(cust2);
		    custlist.add(cust3);
		    
	        message.setContent(buildSmartoneContent(msgId, status, custlist), "text/html;charset=utf-8" );
	        Transport.send( message );
	}

	private static StringBuffer buildHtmlContent(String fileName) throws IOException {
		InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName); // For class files
		//InputStream is = request.getSession().getServletContext().getResourceAsStream(fileName); For WebContent files
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
            br.close();
        }
        return buffer;
	}
	
	private static StringBuffer buildTableContent(ArrayList<String[]> custlist) throws IOException {
        StringBuffer tableBuffer = new StringBuffer("" + 
        		"			Building Id" + 
        		"			Affected Area" + 
        		"			Circuit Id" + 
        		"		");
        for(String[] cust: custlist) {
        	tableBuffer.append(""+cust[0]+""+cust[1]+""+cust[2]+"");
        }
        return tableBuffer;
	}
	
	private static Object buildSmartoneContent(String msgId, String status,
			ArrayList<String[]> custlist) throws IOException {
		String htmlText = "";
		StringBuffer tableBuffer = buildTableContent(custlist);
		String date = DateFormatUtils.format(new Date(), "yyyy/MM/dd HH:mm:ss");
		if ("New".equals(status)) {
			StringBuffer buffer = buildHtmlContent("newTemplate.html");
	        htmlText = MessageFormat.format(buffer.toString(), date, msgId, status, tableBuffer.toString());
		} else {
			StringBuffer buffer = buildHtmlContent("closeTemplate.html");
	        htmlText = MessageFormat.format(buffer.toString(), date, date, msgId, status, "The network problem", tableBuffer.toString());
		}
       
        return htmlText;
	}
}



newTemplate.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="text-align: left;margin-bottom:30px">Dear Customer,</div>

<div style="text-align: left;margin-bottom:30px">Please be informed that we are having a connection issue under the below location, customers under the location may be not able to access internet. Our engineers are performing diagnoses and we will get the problem fixed and get the service back online as soon as possible.
<br/><br/>
We will have further update once available and thank you for the patient.</div>

<div style="text-align: left;margin-bottom:10px">Outage Time: {0}</div>
<div style="text-align: left;margin-bottom:10px">Message ID: {1}</div>
<div style="text-align: left;margin-bottom:10px">Status: {2}</div>

<div style="text-align: left; ">
<table border=1 cellPadding=0 cellSpacing=0 width="700px" style="text-indent:5px;margin-bottom:20px;border-color:black;">{3}</table>
</div>
<div style="text-align: left;margin-top:30px;margin-bottom:15px">Best Regards,</div>
<div style="text-align: left;">IT Shenzhen Support</div>
</body>
</html>

closeTemplate.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="text-align: left;margin-bottom:30px">Dear Customer,</div>

<div style="text-align: left;margin-bottom:30px">Regarding to the service interruption which mention earlier, we are pleased to inform you that the problem has been fixed and we confirm the service is back online. Please also find the reason of outage below for your reference.
<br/><br/>
Thank you again for the patient and understanding and we assure that we will put utmost effort to maintain the service.</div>

<div style="text-align: left;margin-bottom:10px">Outage Time: {0}</div>
<div style="text-align: left;margin-bottom:10px">Resume Time:{1}</div>
<div style="text-align: left;margin-bottom:10px">Message ID: {2}</div>
<div style="text-align: left;margin-bottom:10px">Status: {3}</div>
<div style="text-align: left;margin-bottom:10px">Reason of Outage: {4}</div>

<div style="text-align: left; ">
<table border=1 cellPadding=0 cellSpacing=0 width="700px" style="text-indent:5px;margin-bottom:20px;border-color:black;">{5}</table>
</div>
<div style="text-align: left;margin-top:30px;margin-bottom:15px">Best Regards,</div>
<div style="text-align: left;">IT Shenzhen Support</div>
</body>
</html>

代码Logs:
Java mail实现HTML邮件的发送_第1张图片
发送成功!

你可能感兴趣的:(Java)