💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 如何使用SMTP发邮件? 应用中发送邮件是一个很常见的功能。经过大量用户实践反馈,只推荐一种发邮件的方式,即安装邮件插调用第三方邮件系统的STMP相关账号来进行邮件发送。 不同于LAMP下发送邮件,Windows下,SMTP发送邮件前,需要以下5个步骤: 1. 下载 [javax.mail.jar](https://download.csdn.net/download/u010182075/7145569)包到 *C:\wwwroot\www.example.com/WEB-INF/lib/* 示例目录下 >注意:上传前,如果*C:\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"; String from = "norelpy@smtp.websoft9.cn"; String psd = "WebSoft23221"; String user = "norelpy@smtp.websoft9.cn"; 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. 重启Tomcat。桌面双击Tomcat,单击`General->stop->start`即可 5. 本地浏览器访问:http://服务器公网IP, 如果网页上出现 `Send Email using JSP Result: Sent message successfully.... ` 这样的反馈信息说明邮件发送成功 ## SMTP测试失败 如果使用第三方提供的SMTP服务(如qq邮箱、网易邮箱等),配置也没有问题,但是仍然无法发送邮件。请检查如下两个问题: 1. win+R,输入cmd,验证是否可以连接SMTP,命令如下 ~~~ //测试qq邮箱 端口有465和587 telnet smtp.qq.com 465 //测试网易邮箱 端口有465和994 telnet smtp.163.com 465 ~~~ 如果没有出现 `正在连接smtp....` 这样的反馈信息说明可以连接