Java邮件发送工具类

in with 0 comments

引入Pom依赖

 依赖于apchae email包,maven项目可直接加入以下依赖,普通项目将jar添加进build path即可

<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);
		}
	}
}
Responses /