欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用spring mail发送html邮件的示例代码

程序员文章站 2024-02-27 22:42:33
序 本文展示一下如何使用spring mail来发送html邮件。 maven


本文展示一下如何使用spring mail来发送html邮件。

maven

    <!-- email -->
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-mail</artifactid>
    </dependency>

发送图片

public void send(string from, string[] tomails, string subject, string text,
           map<string,object> inlines) throws exception{
    mimemessage mimemessage = mailsender.createmimemessage();
    mimemessagehelper helper = new mimemessagehelper(mimemessage, true);
    helper.setfrom(from);
    helper.setto(tomails);
    helper.setsubject(subject);
    helper.settext(text, true); //支持html

    // 增加inline
    if(inlines != null){
      for(map.entry<string,object> entry: inlines.entryset()){
        if(entry.getvalue() instanceof classpathresource){
          helper.addinline(entry.getkey(), (resource) entry.getvalue());
        }

      }
    }

    mailsender.send(mimemessage);
  }

测试

发送实例

    classpathresource classpathresource = new classpathresource("image_2.png");
    map<string,object> att = new hashmap<>();
    att.put("image",classpathresource);
    string content = "<html>
              <body>
                <h4>spring mail发送实例</h4>
                <img src='cid:image'/><br>
              </body>
             </html>";
    try{
      mailservice.send(new string[]{"xxxxx@163.com"},"spring mail发送实例",content,att);
    }catch (exception e){
      e.printstacktrace();
    }

异常

org.springframework.mail.mailsendexception: failed messages: com.sun.mail.smtp.smtpsendfailedexception: 554 dt:spm 126 smtp7,dsmowab3u6x1_ldzjiz+aw--.26008s3 1505230070,please see http://mail.163.com/help/help_spam_16.htm?ip=123.65.107.103&hostid=smtp7&time=1505230070
; message exception details (1) are:
failed message 1:
com.sun.mail.smtp.smtpsendfailedexception: 554 dt:spm 126 smtp7,dsmowab3u6x1_ldzjiz+aw--.26008s3 1505230070,please see http://mail.163.com/help/help_spam_16.htm?ip=123.65.107.103&hostid=smtp7&time=1505230070

  at com.sun.mail.smtp.smtptransport.issuesendcommand(smtptransport.java:2267)
  at com.sun.mail.smtp.smtptransport.finishdata(smtptransport.java:2045)
  at com.sun.mail.smtp.smtptransport.sendmessage(smtptransport.java:1260)
  at org.springframework.mail.javamail.javamailsenderimpl.dosend(javamailsenderimpl.java:448)
  at org.springframework.mail.javamail.javamailsenderimpl.send(javamailsenderimpl.java:345)
  at org.springframework.mail.javamail.javamailsenderimpl.send(javamailsenderimpl.java:340)

错误码554

554 dt:spm 发送的邮件内容包含了未被许可的信息,或被系统识别为垃圾邮件。请检查是否有用户发送病毒或者垃圾邮件;

被网易邮箱识别为垃圾邮件了,有个歪招,就是把发送邮箱添加到cc里头

helper.setcc(from);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。