最近在做一个接口项目,需要捕获所有的异常信息,并发送邮件给管理员。使用了JavaMail来实现,然后发现在本地(windows环境)上可以正常发送邮件,而放到了linux环境上就无法发送邮件。相关错误如下:
org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: 220.181.15.111, 25; timeout -1;nested exception is:java.net.ConnectException: Connection timed out (Connection timed out). Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: 220.181.15.111, 25; timeout -1; nested exception is: java.net.ConnectException: Connection timed out (Connection timed out) at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:446) ~[spring-context-support-5.0.6.RELEASE.jar:5.0.6.RELEASE]
重要信息Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host
和25
。首先想到的是linux的端口25没有开通,遂联系相关人员开通,但是可能出于安全考虑没有同意开通。
没办法,只能更换端口了,需要对配置进行修改
原始配置
- spring.mail.host=220.181.15.111 #smtp.126.com 的ip地址
- spring.mail.username=邮箱
- spring.mail.password=权限密码
- spring.mail.default-encoding=UTF-8
修改为
- spring.mail.host=220.181.15.111
- spring.mail.username=邮箱
- spring.mail.password=权限密码
- spring.mail.default-encoding=UTF-8
- spring.mail.properties.mail.smtp.auth=true
- spring.mail.properties.mail.smtp.starttls.enable=true
- spring.mail.properties.mail.smtp.starttls.required=true
- spring.mail.port=465
- spring.mail.properties.mail.smtp.socketFactory.port = 465
- spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
- spring.mail.properties.mail.smtp.socketFactory.fallback = false
之后就可以正常发送邮件了。
而且在linux中可能会出现无法解析域名的问题,这时候可以将smtp主机域名修改为ip地址。ip地址可以使用命令行的ping命令来获取,如下:
顺便讲下spring boot 使用JavaMail发送邮件的方式吧。
首先添加依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-mail</artifactId>
- </dependency>
然后在配置文件(application.properties)中添加mail配置
- spring.mail.host=220.181.15.111
- spring.mail.username=邮箱
- spring.mail.password=权限密码
- spring.mail.default-encoding=UTF-8
- spring.mail.properties.mail.smtp.auth=true
- spring.mail.properties.mail.smtp.starttls.enable=true
- spring.mail.properties.mail.smtp.starttls.required=true
- spring.mail.port=465
- spring.mail.properties.mail.smtp.socketFactory.port = 465
- spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
- spring.mail.properties.mail.smtp.socketFactory.fallback = false
- @Autowired
- JavaMailSender mailSender; //添加依赖后可以直接引用
- public void sendMail(String emailForm,String[] emailTo,String title,String context){
- MimeMessage mimeMessage = mailSender.createMimeMessage();
- MimeMessageHelper helper;
- try {
- helper = new MimeMessageHelper(mimeMessage, true);
- helper.setFrom(emailForm);
- helper.setTo(emailTo);
- helper.setSubject(title);//主题
- helper.setText(context);//正文
- mailSender.send(mimeMessage);
- } catch (MessagingException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }