Java郵件發送工具類


我的博客 地址:https://www.wenhaofan.com/article/20190507104851

引入Pom依賴

 依賴於apchae email包,maven項目可直接加入如下依賴,普通項目將jar添加進build path便可apache

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.2</version>
</dependency>

代碼

public class EmailKit {
	public static String sendEmail(String fromEmail, String toEmail, String title, String content) {
		return sendEmail(null, fromEmail, null, toEmail, title, content);
	}
	public static String sendEmail(String emailServer, String fromEmail, String password, String toEmail, String title, String content) {
		SimpleEmail email=new SimpleEmail();
		if (emailServer!=null) {
			email.setHostName(emailServer);
		}else {
			// 默認使用本地 postfix 發送,這樣就能夠將postfix 的 mynetworks 配置爲 127.0.0.1 或 127.0.0.0/8 了
			email.setHostName("127.0.0.1");
		}
		// 若是密碼爲空,則不進行認證
		if (password!=null) {
			email.setAuthentication(fromEmail, password);
		}
		email.setCharset("utf-8");
		try {
			email.addTo(toEmail);
			email.setFrom(fromEmail);
			email.setSubject(title);
			email.setMsg(content);
			return email.send();
		} catch (EmailException e) {	 
			throw new RuntimeException(e);
		}
	}
}
相關文章
相關標籤/搜索