您现在的位置是:首页 > 文章详情

[Java工具] 邮件发送工具

日期:2018-08-07点击:324

注册邮箱

去163邮箱(或其他邮箱)注册一个邮箱,并开启SMTP授权码。

程序

需要注意的是,由于阿里云服务器不让使用默认的25端口,所以会出现Windows下测试发送邮件成功,Linux服务器下发送邮件却出错的问题(broke pipe、timeout、can not connect等)。解决办法是使用带SSL的465端口。

package com.kuyuntech.util; import java.security.Security; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 邮件发送工具类 */ public class EmailUtils { /** * 发送邮件的方法 * @param toUser :收件人 * @param title :标题 * @param content :内容 */ public static void sendMail(String toUser,String title,String content) throws Exception { // 你自己的邮箱和授权码 final String username = "xxxxx@163.com";//自己的邮箱 final String password = "xxxxxxxxxx";//授权码,需要登录163邮箱,在设置里设置授权码。授权码用于替代密码 Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = System.getProperties(); props.setProperty("mail.smtp.host", "smtp.163.com"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465");// 不能使用25端口,因为阿里云服务器禁止使用25端口,所以必须使用ssl的465端口 props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }}); // -- Create a new message -- Message msg = new MimeMessage(session); // -- Set the FROM and TO fields -- msg.setFrom(new InternetAddress(username)); msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toUser,false)); msg.setSubject(title); msg.setText(content); msg.setSentDate(new Date()); Transport.send(msg); } public static void main(String[] args) throws Exception { sendMail("1802226517@qq.com","标题","Hello!"); } } 
原文链接:https://yq.aliyun.com/articles/643807
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章