使用java mail SMTPTransport发送邮箱,本地秒到,一上服务器就20

编程入门 行业动态 更新时间:2024-10-26 22:21:34

使用java mail SMTPTransport发送<a href=https://www.elefans.com/category/jswz/34/1769795.html style=邮箱,本地秒到,一上服务器就20"/>

使用java mail SMTPTransport发送邮箱,本地秒到,一上服务器就20

一、代码

pom文件

    <dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!--pom.xml添加javax.mail的引用,或者项目引入javax.mail的jar包--><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.2</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>5.3.20</version></dependency>

发送案例

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;public class App {public static void main(String[] args) {Properties property = new Properties();property.put("mail.smtp.auth", "true");// 邮件发送超时设置property.put("mail.smtp.connectiontimeout", 3000);property.put("mail.smtp.timeout", 30000);property.put("mail.smtp.host", "这里是邮箱服务器地址");Authenticator authenticator = new MailAuthenticator("邮箱账号", "密码");try {String sendto = "XXX@qq"; // 接收方Session mailSession = Session.getDefaultInstance(property, authenticator);MimeMessage message = new MimeMessage(mailSession);String nick = "";try {nick = MimeUtility.encodeText("主题");} catch (UnsupportedEncodingException e) {e.printStackTrace();}message.setFrom(new InternetAddress(nick + " <" + "邮箱账号" + ">"));message.setRecipient(Message.RecipientType.TO, new InternetAddress(sendto));message.setSubject("测试邮件");Multipart multipart = new MimeMultipart();BodyPart contentPart = new MimeBodyPart();contentPart.setContent("测试主体", "text/html;charset=UTF-8");multipart.addBodyPart(contentPart);message.setContent(multipart);// 这个是附件,放在本地InputStream inputStream = App.class.getResourceAsStream("/fapiao.pdf");ByteArrayOutputStream output = new ByteArrayOutputStream();byte[] buffer;try {buffer = new byte[inputStream.available()];int n = 0;while (-1 != (n = inputStream.read(buffer))) {output.write(buffer, 0, n);}} catch (IOException e) {e.printStackTrace();}byte[] content = output.toByteArray();// 这里模拟添加三个pdf附件for(int i=0; i<3; i++) {BodyPart attachmentBodyPart = new MimeBodyPart();DataSource source = new ByteArrayDataSource(content, "application/pdf");attachmentBodyPart.setDataHandler(new DataHandler(source));try {attachmentBodyPart.setFileName(MimeUtility.encodeWord("mypdf.pdf"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}multipart.addBodyPart(attachmentBodyPart);}Long start = System.currentTimeMillis();System.out.println("向"+sendto+"发送邮件,附带附件,总大小:"+message.getSize());Transport.send(message);System.out.println("邮件发送成功,耗时="+(System.currentTimeMillis()-start)+"ms");} catch (MessagingException e) {e.printStackTrace();}return;}
}

二、现象

在本地测试,几秒就收到了邮箱,但是在服务器发送,就20-30s左右才可以收到。在生产环境,有大量邮件发送堆积,直接导致发送失败。

报错信息:

Could not connect to SMTP host: mail.bjgas, port: 25, response: 421]

邮件发送异常EOF

 三、排查

1、跟踪 

通过跟踪本地邮件发送程序源码,最终发现是服务器没有在hosts配置本机的主机名导致的。

 

通过上面代码跟踪发现,在执行 ehlo xxx 时,xxx的值默认会调 getlocalHost() ,因为刚开始进来localHostName为空,所以去调用 InetAddress.getLocalHost()方法。又通过InetAddress.getAddressesFromNameService(local, null); 方法获取服务器本地ip。

最终调用 nameService.lookupAllHostAddr(host) 方法,当 hosts 文件中没有添加主机名时,getaddrinfo 调用返回错误码,此时 jdk 会转而调用 lookupIfLocalhost 方法,它内部调用了操作系统的 getifaddrs 方法,以获取本机所有 ip 地址(我这边光这一步就花费10s左右);当获取到所有的ip地址后,进行一系列解析处理,最终导致发送邮件的时候发送慢、超时或其他报错。

2. 总结:

当 hosts 文件中没有添加主机名时,会返回本机所有的 ip 地址;

当 hosts 文件中添加主机名后,只会返回配置的 127.0.01 的 ip 地址;

四、解决方案

1、在本地的/etc/hosts文件配置本地ip或域名与主机名对应;(建议都配置)

127.0.0.1 hostname
ip/域名  hostname

2、在代码里写入加入配置,不让它默认调getlocalhost()方法

 property.put("mail.smtp.localhost","主机名称");property.put("mail.smtp.localaddress","主机ip");

方法2还没有验证,请谨慎使用。 

更多推荐

使用java mail SMTPTransport发送邮箱,本地秒到,一上服务器就20

本文发布于:2023-12-05 08:33:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1663681.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:邮箱   服务器   mail   java   SMTPTransport

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!