java中,发送邮件可以使用 commons-email.jar
首先我们需要找到对应的jar,可以手动下载,或者直接maven;
maven地址如下:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-email --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.5</version> </dependency>
测试例子:
import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; public class EmailTest { public static void main(String[] args) { String htmlContent = "你好!<br/>你的验证码为:<span style='font-size: 20px;color: #009688'> 54ZSD25 </span>(10分钟内有效)<br/>"; EmailP email = new EmailP(); email.setHostName("smtp.aliyun.com"); email.setUserName("用户名"); email.setUserPwd("密码"); email.setNickName("发送者昵称"); email.setToEmail("接受者邮箱"); email.setTitle("邮箱标题"); email.setHtmlContent(htmlContent); System.out.println(sendHtmlEmail(email)); } /** * <p> 方法描述:发送html邮件. </p> * <p> 创建时间:2017-12-15 11:32:18 </p> * <p> 创建作者:lixingwu </p> * * @return 发送成功返回 * @author "lixingwu" */ public static String sendHtmlEmail(EmailP emailP) { HtmlEmail email = new HtmlEmail(); String result = ""; try { email.setTLS(true); email.setDebug(false); email.setSSL(true); email.setHostName(emailP.getHostName()); email.setAuthenticator(new DefaultAuthenticator(emailP.getUserName(), emailP.getUserPwd())); email.setFrom(emailP.getUserName(), emailP.getNickName()); email.addTo(emailP.getToEmail()); email.setCharset("UTF-8"); email.setSubject(emailP.getTitle()); email.setHtmlMsg(emailP.getHtmlContent()); result = email.send(); } catch (EmailException e) { result = ""; e.printStackTrace(); } return result; } static class EmailP { private String hostName; private String userName; private String nickName; private String userPwd; private String toEmail; private String title; private String htmlContent; public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public String getToEmail() { return toEmail; } public void setToEmail(String toEmail) { this.toEmail = toEmail; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getHtmlContent() { return htmlContent; } public void setHtmlContent(String htmlContent) { this.htmlContent = htmlContent; } } }