代碼在本地發郵件沒任何問題。但部署到服務器,發送郵件顯示鏈接異常。一開始很是懵逼,以後telnet smtp.163.com 25不通,發現是雲服務器出於安全考慮,關閉了服務器的25端口,而25端口是smtp的默認端口。以後telnet smtp.163.com 465能通(郵件服務商的加密的465端口)。html
一、POM文件配置:java
<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>
二、spring 配置:python
<!-- 郵箱配置 --> <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>
三、代碼實例:spring
/**
* 組織郵件信息併發送郵件
*
* @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服務器