JavaMail 工具

郵件發送工具類:html

1.兩種郵件發送格式,Gmail和126郵箱。java

2.JavaMail發送郵件須要注意郵箱安全設置。web

A.GMail 發送郵件設置spring

Google has been so kind as to list all the potential problems and fixes for us. Although I recommend trying the less secure apps setting. Be sure you are applying these to the correct account.安全

  • If you've turned on 2-Step Verification for your account, you might need to enter an App password instead of your regular password.
  • Sign in to your account from the web version of Gmail at https://mail.google.com. Once you’re signed in, try signing in
    to the mail app again.
  • Visit http://www.google.com/accounts/DisplayUnlockCaptcha and sign in with your Gmail username and password. If asked, enter the
    letters in the distorted picture.
  • Your app might not support the latest security standards. Try changing a few settings to allow less secure apps access to your account.
  • Make sure your mail app isn't set to check for new email too often. If your mail app checks for new messages more than once every 10
    minutes, the app’s access to your account could be blocked.

B.126設置比較簡單,只須要設置「POP3/SMTP/IMAP」,‘設置’->'POP3/SMTP/IMAP'->'IMAP/SMTP服務'。session

添加依賴:app

'com.sun.mail:all:1.5.6',
'javax.mail:mail:1.5.0-b01',
'javax.activation:activation:1.1.1',

email.properties 郵箱帳號配置信息。less

# email properties test
host=smtp.163.com
from=info@163.com
username=info@163.com
password=111111
to=info@163.com
port=25
#isSSL=true
#connectionTimeout=10000

spring讀取配置文件socket

<!-- 郵件帳號配置信息 -->
	<bean id="emailProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
		<property name="locations">
			<list>
				<value>classpath:email.properties</value>
			</list>
		</property>
	</bean>

EmailUtilBean.java 發送郵件帳號信息,經過spring注入properties配置文件信息。ide

import java.util.Properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author rico
 * 郵件帳號信息Bean
 */
@Component(value="emailUtilBean")
public class EmailUtilBean {
	
	// 默認連接超時時間
	private static final int DEFAULT_CONNECTION_TIMEOUT = 10000;
	
	@Value("#{emailProperties.host}")
	private String host;
	
	@Value("#{emailProperties.from}")
	private String from;
	
	@Value("#{emailProperties.username}")
	private String username;
	
	@Value("#{emailProperties.password}")
	private String password;
	
	@Value("#{emailProperties.to}")
	private String to;
	
	@Value("#{emailProperties.port}")
	private String port;
	
	@Value("#{emailProperties.isSSL}")
	private boolean isSSL = false;
	
	@Value("#{emailProperties.connectionTimeout}")
	private Integer connectionTimeout;
	
	public EmailUtilBean() {}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}
	
	public Properties getProperties() {         
		Properties props = new Properties();         
		props.put("mail.smtp.host", this.host);         
		props.put("mail.smtp.port", this.port);         
		props.put("mail.smtp.starttls.enable", "true");
		
		if(connectionTimeout==null || connectionTimeout==0) {
			connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
		}
		props.put("mail.smtp.connectiontimeout", connectionTimeout);
		
		// If you need to authenticate
		props.put("mail.smtp.auth", "true");         
		//props.put("mail.smtp.auth", validate ? "true" : "false");                                      
		
		// Use the following if you need SSL
		if(isSSL) {
			props.put("mail.smtp.socketFactory.port", this.port);      
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");       
			props.put("mail.smtp.socketFactory.fallback", "false");
		}
		
		return props;
	}
	
	@Override
	public String toString() {
		return new StringBuilder()
				.append("EmailAccount=[")
				.append(", host=").append(host)
				.append(", from=").append(from)
				.append(", username=").append(username)
				.append(", password=").append(password)
				.append(", to=").append(to)
				.append("]")
				.toString();
	}
	
}

 

EmailUtil.java

/**
 * 
 */
package org.rico.commons.utils.email;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 郵件工具
 * @author rico
 *
 */
public class EmailUtil {
	private static final Logger logger = LoggerFactory.getLogger(EmailUtil.class);
	private static final boolean DEFAULT_DEBUG_MODE = false;
	
	// 是否啓用調試
	private boolean debug = DEFAULT_DEBUG_MODE;
	
	private EmailUtilBean emailUtilBean;
	private Properties props;
	private Authenticator authenticator;
	
	public EmailUtil(EmailUtilBean emailUtilBean) {
		this.emailUtilBean = emailUtilBean;
		this.props = emailUtilBean.getProperties();
		
		this.authenticator = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(emailUtilBean.getUsername(), emailUtilBean.getPassword());
			}
		};
	}
	
	public void sendText(String subject, String content) throws Exception {
		
		// Get the Session object.
		Session session = Session.getInstance(props, authenticator);
		session.setDebug(debug);
		
		try {
			// Create a default MimeMessage object.
			Message message = new MimeMessage(session);
			
			// Set From: header field of the header.
			message.setFrom(new InternetAddress(this.emailUtilBean.getFrom()));
			
			// Set To: header field of the header.
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(this.emailUtilBean.getTo()));
			
			// Set Subject: header field
			message.setSubject(subject);
			
			// Now set the actual message
			message.setText(content);
			
			// Send message
			Transport.send(message);
			logger.info("Sent message successfully");

		} catch (MessagingException e) {
			logger.error("Send message error...", e);
			throw e;
		}
	}
	
	/**
	 * send html format email
	 * @param subject
	 * @param content
	 * @return
	 */
	public boolean sendHtml(String subject, String content) {
		// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
		
		Session session = Session.getDefaultInstance(props, authenticator);
		session.setDebug(debug);
		
		try {
			// 根據session建立一個郵件消息 
			Message mailMessage = new MimeMessage(session); 
			
			// 建立郵件發送者地址 
			Address from = new InternetAddress(this.emailUtilBean.getFrom()); 
			
			// 設置郵件消息的發送者
			mailMessage.setFrom(from); 
			
			// 建立郵件的接收者地址,並設置到郵件消息中 
			Address to = new InternetAddress(this.emailUtilBean.getTo()); 
			
			// Message.RecipientType.TO屬性表示接收者的類型爲TO
			mailMessage.setRecipient(Message.RecipientType.TO, to); 
			
			// 設置郵件消息的主題
			mailMessage.setSubject(subject); 
			
			// 設置郵件消息發送的時間
			mailMessage.setSentDate(new Date()); //
			
			// MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象 
			Multipart mainPart = new MimeMultipart(); 
			
			// 建立一個包含HTML內容的MimeBodyPart 
			BodyPart html = new MimeBodyPart(); 
			
			// 設置HTML內容 
			html.setContent(content, "text/html; charset=utf-8"); 
			mainPart.addBodyPart(html); 
			
			// 將MiniMultipart對象設置爲郵件內容 
			mailMessage.setContent(mainPart); 
			
			// 發送郵件
			Transport.send(mailMessage); 
			return true;
			
		} catch (MessagingException ex) { 
			logger.error("發送郵件信息發送錯誤.", ex); 
		} 
		return false;
	}

	public boolean isDebug() {
		return debug;
	}

	public void setDebug(boolean debug) {
		this.debug = debug;
	}
	
}
相關文章
相關標籤/搜索