代码在本地发邮件没任何问题。但部署到服务器,发送邮件显示连接异常。一开始非常懵逼,之后telnet smtp.163.com 25不通,发现是云服务器出于安全考虑,关闭了服务器的25端口,而25端口是smtp的默认端口。之后telnet smtp.163.com 465能通(邮件服务商的加密的465端口)。
1、POM文件配置:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies>
2、spring 配置:
<!-- 邮箱配置 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.163.com" />
<property name="username" value="********" />
<property name="password" value="********" />
<property name="port" value="465" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">50000</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<!-- <prop key="mail.debug">true</prop> -->
<prop key="mail.smtp.socketFactory.port">465</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
</props>
</property>
</bean>
3、代码实例:
/**
* 组织邮件信息并发送邮件
*
* @param toAddress
* @param fromAddress
* @param subject
* @param htmlBody
* @throws MessagingException
*/
public void sendHtmlEmail(String toAddress, String fromAddress, String subject, String htmlBody)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
helper.setTo(toAddress);
helper.setFrom(fromAddress);
helper.setText(htmlBody, true);
helper.setSubject(subject);
mailSender.send(message);
}
this.sendHtmlEmail("18753377533@163.com", "sender@163.com", "找回您的账户密码", emailContent);
https://www.cnblogs.com/dixinyunpan/p/6041278.html
https://blog.csdn.net/yuruixin_china/article/details/73276390