spring JavaMailSender 发送邮件

  1. 配置JavaMailSenderImpl类
**
 * @Configuration 表示是配置类
 * @ComponentScan("com") 需要扫描的包路径
 * @PropertySource("classpath:mail.properties") 需要加载的配置文件
 */

@Configuration
@ComponentScan("com")
@PropertySource("classpath:mail.properties")
public class MailConfig {
    /**
     * 配置发送邮件核心类 JavaMailSenderImpl
     * @param env
     * @return  发送邮件核心类
     */
    @Bean
    public JavaMailSenderImpl mailSender(Environment env){
        JavaMailSenderImpl mailSender=new JavaMailSenderImpl();
        mailSender.setHost(env.getProperty("mailserver.host"));
        mailSender.setPort(Integer.parseInt(env.getProperty("mailserver.port")));
        mailSender.setUsername(env.getProperty("mailserver.username"));
        //密码,这里不是邮箱的密码,而是开启服务器后,生成的授权码pgfvqmnnczrggfae env.getProperty("mailserver.password")
        mailSender.setPassword("uajdyjpnrvxejcae");
        //ssl加密,需要加,否则无法运行
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        Properties props = System.getProperties();
        //开启授权,否则报535错误
        props.put("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);


        mailSender.setJavaMailProperties(props );
        return mailSender;
    }

    /**
     *配置发送邮件的模板
     * @return
     */
    @Bean
    public VelocityEngineFactoryBean velocityEngineFactoryBean(){
        VelocityEngineFactoryBean velocityEngine=new VelocityEngineFactoryBean();
        Properties properties=new Properties();
            properties.setProperty("resource.loader","class");
            properties.setProperty("class.resource.loader.class",ClasspathResourceLoader.class.getName());
        velocityEngine.setVelocityProperties(properties);
        return velocityEngine;
    }
}

2.实现发送邮件功能实现类

/**
 *  注入 JavaMailSender类,会自动去寻找配置发送邮件的核心类
 */
@Service("MailService")
public class MailServiceImpl  implements MailService{
    @Autowired
    private JavaMailSender mailSender; //发送邮件功能
    @Autowired
    VelocityEngine velocityEngine;  //配置模板


    /**
     *  发送简单邮件
     * @param to
     * @param spittle
     */
    @Override
    public void sendSimpleSpittleEmail(String to, Spittle spittle) {
           //通过这个对象封装信息,相当于信封
        SimpleMailMessage message = new SimpleMailMessage();
           //获取spittle对象中的收件人名字
        String spitterName = spittle.getSpitter().getFullName();
           //发件人
        message.setFrom("1505742009@qq.com");
          //收件人
        message.setTo(to);
            //邮件主题
        message.setSubject("New spittle from " + spitterName);
            //邮件内容
        message.setText(spitterName + " says: " + spittle.getText());
             //发送邮件
        mailSender.send(message);
    }

    /**
     *  发送有附件的邮件
     * @param to
     * @param spittle
     * @throws MessagingException
     */
    @Override
    public void sendSpittleEmailWithAttachment(String to, Spittle spittle) throws MessagingException {
          //通过邮件发送器的createMimeMessage方法构建可含附件的邮件
        MimeMessage message = mailSender.createMimeMessage();
            // 第一个参数是邮件的对象
            // 第二个参数为true表示这个消息是multipart类型的消息(表示是带有附件的邮件)
           // 第三个参数是防止中文乱码
        MimeMessageHelper helper = new MimeMessageHelper(message,true,"utf-8");
           //获取收件人名,用于后面发送邮件做主题
        String spitterName = spittle.getSpitter().getFullName();
           //寄件人
        helper.setFrom("1505742009@qq.com");
           //收件人
        helper.setTo(to);
           //邮件的主题内容
        helper.setSubject("JavaMail Test");
        Map<String,Object> model=new HashMap<String,Object >();
        model.put("spitterName",spitterName);
        model.put("spittleText",spittle.getText());
        String emailTest= VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,"/templates/emailTemplate.vm",model);
        //邮件的发送内容emailTest 是模板
        helper.setText(emailTest,true); //发送模板邮件
         // helper.setText(spitterName + " says: " + spittle.getText()); //简单信息
         //通过路径获取图片附件
        ClassPathResource couponImage = new ClassPathResource("/document/new1.txt");
         //第一个参数是图片的名称,到时候收件人收到的附件名
         //第二个参数是图片附件的资源
        helper.addAttachment("new1.txt", couponImage);
         //send方法是发送邮件的方法
        mailSender.send(message);
    }


    /**
     * 发送有内联图片的邮件
     * @param to
     * @param spittle
     * @throws MessagingException
     */
    @Override
    public void sendRichSpitterEmail(String to, Spittle spittle) throws MessagingException {

              //创建一封富文本邮件
            MimeMessage message=mailSender.createMimeMessage();
              //第二个参数表明传递进来的第一个参数是html文本
            MimeMessageHelper helper=new MimeMessageHelper(message,true,"utf-8");
               //发件人
            helper.setFrom("1505742009@qq.com");
               //收件人
            helper.setTo(to);
               //发送的邮件主题
            helper.setSubject("New spittle from " + spittle.getSpitter().getFullName());
              //cid:spitterLogo,标记一个变量,后面为这个变量添加一张图片
              //第二个参数表示传递的第一个参数是html
            helper.setText("<html><body><img src='cid:spittleLogo'>"+"<h4>"+
                    spittle.getSpitter().getFullName()+"says...</h4>"+"<i>"+spittle.getText()+
                    "</i>"+"</body></html>",true);
             //创建一个变量存放图片
            ClassPathResource image=new ClassPathResource("/img/coupon.jpg");
             //为消息添加嵌入式的图片
            helper.addInline("spittleLogo", image);
             //发送邮件
            mailSender.send(message);

    }
}

3.配置文件

#qq的服务器名
mailserver.host=smtp.qq.com
#端口号
mailserver.port=465
#你的邮箱号
mailserver.username=1505742009@qq.com
#第一步获取到的授权码
mailserver.password=altfwaxzpvkwifda

4.模板类

<html>
<body>
<img src="">
<h4>
    ${spitterName}  你好啊,这是模板邮件啊!
</h4>
<i>
    ${spittleText}
</i>
</body>

</html>
  1. 测试类
/**
 * @ContextConfiguration 加載配置类
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=MailConfig.class)
public class TestMail {
@Autowired
private MailService mailService;

    @Test
    public void sendSimpleSpittleEmail() throws Exception {
/*        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:config/spring.xml");
        MailService mailService=(MailService) ctx.getBean("MailService");*/
        Spitter spitter = new Spitter("周瑞珣", null, "pipi", "1551124145@qq.com", true);
        Spittle spittle = new Spittle(spitter);
        //第一个参数是收件人,第二个参数是邮件
        //普通邮件
        //mailService.sendSimpleSpittleEmail(spitter.getEmail(), spittle);
        //携带附件
        mailService.sendSpittleEmailWithAttachment(spitter.getEmail(), spittle);
        //内联图片
        // mailService.sendRichSpitterEmail(spitter.getEmail(),spittle);

    }

原文地址:https://blog.csdn.net/wang_97/article/details/79851437

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值