楔子
spring邮件发送在云服务器失败
阿里云的服务是专有网络主机25端口已经被阿里云屏蔽无法使用
云平台安全规则:https://help.aliyun.com/knowledge_detail/37353.html
配置文件
<!-- 加载mail.properties文件 -->
<!-- http://blog.sina.com.cn/s/blog_5a15b7d10102w4k2.html spring只会加载一个配置文件,其他的会忽略 -->
<context:property-placeholder location="classpath:conf/mail.properties" ignore-unresolvable="true" />
<!-- 配置一个简单邮件对象 -->
<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="${mail.from}"></property>
</bean>
<!-- 邮件的发送对象 -->
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="defaultEncoding" value="${maiL.encoding}"></property>
<property name="host" value="${mail.smtp.host}"></property>
<property name="username" value="${mail.username}"></property>
<property name="password" value="${mail.password}"></property>
<!-- 邮件发送相关的配置信息 -->
<property name="javaMailProperties">
<props>
<!-- 让服务器检验用户密码是否正确 -->
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.debug">${mail.debug}</prop>
<prop key="mail.smtp.timeout">0</prop>
<!-- 如果使用默认25端口,下面这2个不需要配置 -->
<prop key="mail.smtp.socketFactory.class">${mail.smtp.socketFactory.class}</prop>
<prop key="mail.smtp.port">${mail.smtp.socketFactory.port}</prop>
</props>
</property>
</bean>
maiL.encoding=UTF-8
mail.smtp.host=smtp.163.com
mail.smtp.auth=true
mail.debug=true
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
##此处不用写@163.com也行
mail.username=***
mail.password=***
mail.from=***@163.com
spring邮件发送
可以直接参考spring官网
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("mail.host.com");
MimeMessage message = sender.createMimeMessage();
// use the true flag to indicate you need a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo("test@host.com");
//identifier1234 带附件
// use the true flag to indicate the text included is HTML
helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);
// let's include the infamous windows Sample file (this time copied to c:/)
FileSystemResource res = new FileSystemResource(new File("c:/Sample.jpg"));
helper.addInline("identifier1234", res);
sender.send(message);
后记
学习笔记