You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中使用JavaEmailSender配置代理后连接超时如何解决

解决方案

问题根因

  • 代理配置缺少Spring Boot识别的统一前缀,未被加载到JavaMail运行参数中,导致代理未生效
  • 代理host地址错误携带了http://协议头,JavaMail无法正确识别代理地址
  • 若依赖版本过低,会不支持SMTP HTTP代理配置,同样会导致直连超时

第一步:修正application.properties配置

替换原有错误的代理配置,完整配置如下:

# 原有邮件配置保留
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=myemail@gmail.com
spring.mail.password=qypaaboydxppgpck
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

# 修正后的代理配置:添加统一前缀、去掉host的http://协议头
spring.mail.properties.mail.smtp.proxy.host=proxy
spring.mail.properties.mail.smtp.proxy.port=8080
spring.mail.properties.mail.smtp.proxy.user=username
spring.mail.properties.mail.smtp.proxy.password=*******

# 可选:添加超时配置避免无限制等待
spring.mail.properties.mail.smtp.connectiontimeout=10000
spring.mail.properties.mail.smtp.timeout=10000

第二步:修正业务代码(自动配置不生效时使用)

你现有代码中Properties props = emailSender.;未编写完成,可通过手动获取JavaMailImpl的属性对象确认配置加载,也可直接手动注入代理参数:

@Autowired
private JavaMailSender emailSender;

@Autowired
SpringTemplateEngine templateEngine;

public void sendSimpleMessage(String to, String subject, List<SiteMailDTO> listSiteMailDTO) throws MessagingException {
    // 手动获取配置确认代理属性已加载
    JavaMailSenderImpl mailSenderImpl = (JavaMailSenderImpl) emailSender;
    Properties props = mailSenderImpl.getJavaMailProperties();
    // 若配置未自动注入,可取消下方注释手动添加代理参数
    // props.put("mail.smtp.proxy.host", "proxy");
    // props.put("mail.smtp.proxy.port", "8080");
    // props.put("mail.smtp.proxy.user", "username");
    // props.put("mail.smtp.proxy.password", "*******");

    MimeMessage message = emailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, StandardCharsets.UTF_8.name());

    Map<String, Object> model = new HashMap<>();
    model.put("sites", listSiteMailDTO);

    Context context = new Context();
    context.setVariables(model);
    String html = templateEngine.process("email-template", context);

    helper.setTo(to);
    helper.setText(html, true);
    helper.setSubject(subject);
    emailSender.send(message);
}

第三步:额外验证项

  • 确认你的com.sun.mail:jakarta.mail或com.sun.mail:javax.mail依赖版本在1.6.0及以上,低于该版本不支持SMTP HTTP代理配置,需升级依赖
  • 手动测试代理服务器连通性:在部署服务的机器上执行telnet proxy 8080、curl -x proxy:8080 smtp.gmail.com:587确认代理可正常访问SMTP服务
  • 若你使用的是SOCKS类型代理,需将配置中的smtp.proxy替换为socks.proxy即可

内容的提问来源于stack exchange,提问作者Bilal Dekar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 23:45:03