ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 如何使用SMTP发邮件? 应用中发送邮件是一个很常见的功能。经过大量用户实践反馈,只推荐一种发邮件的方式,即安装邮件插调用第三方邮件系统的STMP相关账号来进行邮件发送。 如果您的应用自带了SMTP模块,且您已经成功发送邮件,下面的文档跳过。 如果您认为自己的SMTP账号准确无误,仍然无法发送邮件,那么您一定开始怀疑镜像有问题。下面是一个SMTP的小程序,用于测试SMTP。具体测试步骤: 1. 下载 [javax.mail.jar](https://download.csdn.net/download/u010182075/7145569)包到 /data/wwwroot/www.example.com/WEB-INF/lib 示例目录下 >注意:上传前,如果 /data/wwwroot/www.example.com/ 目录下存在其他文件,请将其清空后再上传 2. 新建一个以.jsp后缀的文件,假设命名为“index.jsp”,将其放到与 */WEB-INF* 目录同级上 3. 拷贝下面的测试程序到index.jsp文件中,并保存 ``` <%@ page import="java.util.*" %> <%@ page import="javax.mail.*" %> <%@ page import="javax.mail.internet.*" %> <%@ page import="javax.activation.*" %> <% String result; // 收信方Email String to = "***********@qq.com"; //SMTP账号 --开始 String from = "norelpy@smtp.websoft9.cn"; String psd = "Websoft9"; String user = "norelpy@smtp.websoft9.cn"; //SMTP账号---结束 Properties properties = new Properties(); try { properties.setProperty( "mail.smtp.auth", "true" ); properties.setProperty( "mail.transport.protocol", "smtp" ); properties.setProperty( "mail.smtp.host", "smtpdm.aliyun.com" ); // SSL properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("mail.smtp.socketFactory.fallback", "false"); properties.setProperty("mail.smtp.socketFactory.port", "465"); properties.setProperty("mail.smtp.port", "465"); Session mailSession = Session.getDefaultInstance( properties ); Message message = new MimeMessage( mailSession ); Transport transport = mailSession.getTransport(); message.setFrom( new InternetAddress( from ) ); message.addRecipient( Message.RecipientType.TO, new InternetAddress( to ) ); message.setSubject( "This is the Subject Line!" ); BodyPart messageBodyPart = new MimeBodyPart(); //邮件信息内容 messageBodyPart.setText("This is message body"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); message.setSentDate(new Date()); transport.connect(user,psd); transport.sendMessage( message, message.getAllRecipients() ); result = "Sent message successfully...."; } catch (Exception e) { e.printStackTrace(); result = "Error: unable to send message...."; } %> <html> <head> <title>Send Email using JSP</title> </head> <body> <center> <h1>Send Email using JSP</h1> </center> <p align="center"> <% out.println("Result: " + result + "\n"); %> </p> </body> </html> ``` 4. 将示例中的收件邮箱、SMTP账号更改成您自己的账号 5. 重启Tomcat 6. 本地浏览器访问:http://服务器公网IP, 如果网页上出现 *Send Email using JSP Result: Sent message successfully....* 这样的反馈信息说明邮件发送成功 ## SMTP测试失败 1. 登录服务器,验证是否可以连接SMTP,命令如下 ~~~ //安装telnet yum install telnet -y //测试qq邮箱 端口有465和587 telnet smtp.qq.com 465 //测试网易邮箱 端口有465和994 telnet smtp.163.com 465 ~~~ 如果出现 `220 smtp.*.com Esmtp *Mail Server `或者 `Escape character is '^]'` 这样的反馈信息说明可以连接 > 注意:本地Telnet测试成功,不代表服务器Telnet成功,因为您的服务器IP地址由于某些原因可能会被STMP服务器列入黑名单。