zoukankan      html  css  js  c++  java
  • 使用Spring的MailSender发送邮件

    第1步:扫描邮件发送的属性配置

    <context:property-placeholder location="/config/mail.properties" ignore-unresolvable="true" />

    mail.properties

    mailServerHost=your host
    mailServerPort=25
    mailUserName= your name
    mailPassword= your password
    mailFromAddress= xijinping@china.com


    第2步:配置bean
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host">
    <value>${mailServerHost}</value>
    </property>
    <property name="port">
    <value>${mailServerPort}</value>
    </property>
    <property name="javaMailProperties">
    <props>
    <prop key="mail.smtp.auth">true</prop>
    <prop key="mail.smtp.timeout">25000</prop>
    </props>
    </property>
    <property name="username">
    <value>${mailUserName}</value> <!-- 发送者用户名 -->
    </property>
    <property name="password">
    <value>${mailPassword}</value> <!-- 发送者密码 -->
    </property>
    <!-- <property name="from">
     <value>${mailFromAddress}</value>
    </property> -->

    </bean>

    第3步:注入bean

    @Service
    public class MailService {


    @Resource
    private JavaMailSender mailSender;

    @Value("${mailFromAddress}")
    private String mailFromAddress;

    public void send(String subject,String content,String to){
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    simpleMailMessage.setSubject(subject);
    simpleMailMessage.setText(content);
    simpleMailMessage.setFrom(mailFromAddress);
    simpleMailMessage.setTo(to);
    mailSender.send(simpleMailMessage);
    }
    }


    第4步:调用API发送

    mailService.send();


    注意事项:

    需要特别注意,userName是用来连接服务器的,from参数是可以手动设置的。
    from和userName可以不同。

    from参数也是必须的,通过@Value注解注入到Java代码中。

  • 相关阅读:
    桂林印象
    快变
    近期的事
    *C#中使用ref和out一点认识!*
    *在框架集页面放置TreeView控件时页面跳转的问题解决*
    *无法找到脚本库的问题*
    *Ajax.Net快速入门*
    *网页过期*
    *Prototype开发笔记*
    *正则表达式*
  • 原文地址:https://www.cnblogs.com/qitian1/p/6462502.html
Copyright © 2011-2022 走看看