当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot整合邮件发送与注意事项

Spring Boot整合邮件发送与注意事项

2019年07月19日  | 移动技术网IT编程  | 我要评论

什么是spring boot

spring boot是一个框架,其设计目的是简化spring应用的初始搭建配置以及开发过程。该框架使用了特定的配置方式,从而使开发人员不在需要定义样板化的配置。

spring boot的好处

1、配置简单;

2、编码简单;

3、部署简单;

4、监控简单;

概述

spring boot下面整合了邮件服务器,使用spring boot能够轻松实现邮件发送;整理下最近使用spring boot发送邮件和注意事项;

maven包依赖

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

spring boot的配置

spring.mail.host=smtp.servie.com
spring.mail.username=用户名 //发送方的邮箱
spring.mail.password=密码 //对于qq邮箱而言 密码指的就是发送方的授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=false #是否用启用加密传送的协议验证项
spring.mail.properties.mail.smtp.starttls.required=fasle #是否用启用加密传送的协议验证项
#注意:在spring.mail.password处的值是需要在邮箱设置里面生成的授权码,这个不是真实的密码。

spring 代码实现

package com.dbgo.webservicedemo.email;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.core.io.filesystemresource;
import org.springframework.mail.javamail.javamailsender;
import org.springframework.mail.javamail.mimemessagehelper;
import org.springframework.stereotype.component;

import javax.mail.messagingexception;
import javax.mail.internet.mimemessage;
import java.io.file;

@component("emailtool")
public class emailtool {
 @autowired
 private javamailsender javamailsender;


 public void sendsimplemail(){
  mimemessage message = null;
  try {
   message = javamailsender.createmimemessage();
   mimemessagehelper helper = new mimemessagehelper(message, true);
   helper.setfrom("jiajinhao@dbgo.cn");
   helper.setto("653484166@qq.com");
   helper.setsubject("标题:发送html内容");

   stringbuffer sb = new stringbuffer();
   sb.append("<h1>大标题-h1</h1>")
     .append("<p style='color:#f00'>红色字</p>")
     .append("<p style='text-align:right'>右对齐</p>");
   helper.settext(sb.tostring(), true);
   filesystemresource filesystemresource=new filesystemresource(new file("d:\76678.pdf"))
   helper.addattachment("电子发票",filesystemresource);
   javamailsender.send(message);
  } catch (messagingexception e) {
   e.printstacktrace();
  }
 }
}

非spring boot下发送电子邮件:

maven包依赖

<dependencies>
  <dependency>
   <groupid>com.sun.mail</groupid>
   <artifactid>javax.mail</artifactid>
   <version>1.5.2</version>
  </dependency>
 </dependencies>

demo1代码事例

package com.justin.framework.core.utils.email;

import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.unsupportedencodingexception;
import java.util.date;
import java.util.properties;

import javax.activation.datahandler;
import javax.activation.datasource;
import javax.activation.filedatasource;
import javax.mail.address;
import javax.mail.authenticator;
import javax.mail.message;
import javax.mail.message.recipienttype;
import javax.mail.messagingexception;
import javax.mail.passwordauthentication;
import javax.mail.session;
import javax.mail.transport;
import javax.mail.internet.internetaddress;
import javax.mail.internet.mimebodypart;
import javax.mail.internet.mimemessage;
import javax.mail.internet.mimemultipart;
import javax.mail.internet.mimeutility;

/**
 * 使用smtp协议发送电子邮件
 */
public class sendemailcode {


 // 邮件发送协议
 private final static string protocol = "smtp";

 // smtp邮件服务器
 private final static string host = "mail.tdb.com";

 // smtp邮件服务器默认端口
 private final static string port = "25";

 // 是否要求身份认证
 private final static string is_auth = "true";

 // 是否启用调试模式(启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息)
 private final static string is_enabled_debug_mod = "true";

 // 发件人
 private static string from = "tdbjrcrm@tdb.com";

 // 收件人
 private static string to = "db_yangruirui@tdbcwgs.com";

 private static string sendusername="tdbjrcrm@tdb.com";
 private static string senduserpwd="new*2016";

 // 初始化连接邮件服务器的会话信息
 private static properties props = null;

 static {
  props = new properties();
  props.setproperty("mail.enable", "true");
  props.setproperty("mail.transport.protocol", protocol);
  props.setproperty("mail.smtp.host", host);
  props.setproperty("mail.smtp.port", port);
  props.setproperty("mail.smtp.auth", is_auth);//视情况而定
  props.setproperty("mail.debug",is_enabled_debug_mod);
 }


 /**
  * 发送简单的文本邮件
  */
 public static boolean sendtextemail(string to,int code) throws exception {
  try {
   // 创建session实例对象
   session session1 = session.getdefaultinstance(props);

   // 创建mimemessage实例对象
   mimemessage message = new mimemessage(session1);
   // 设置发件人
   message.setfrom(new internetaddress(from));
   // 设置邮件主题
   message.setsubject("内燃机注册验证码");
   // 设置收件人
   message.setrecipient(recipienttype.to, new internetaddress(to));
   // 设置发送时间
   message.setsentdate(new date());
   // 设置纯文本内容为邮件正文
   message.settext("您的验证码是:"+code+"!验证码有效期是10分钟,过期后请重新获取!"
     + "中国内燃机学会");
   // 保存并生成最终的邮件内容
   message.savechanges();

   // 获得transport实例对象
   transport transport = session1.gettransport();
   // 打开连接
   transport.connect("meijiajiang2016", "");
   // 将message对象传递给transport对象,将邮件发送出去
   transport.sendmessage(message, message.getallrecipients());
   // 关闭连接
   transport.close();

   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }

 public static void main(string[] args) throws exception {
  sendhtmlemail("db_yangruirui@tdbcwgs.com", 88888);
 }

 /**
  * 发送简单的html邮件
  */
 public static boolean sendhtmlemail(string to,int code) throws exception {
  // 创建session实例对象
  session session1 = session.getinstance(props, new myauthenticator());

  // 创建mimemessage实例对象
  mimemessage message = new mimemessage(session1);
  // 设置邮件主题
  message.setsubject("内燃机注册");
  // 设置发送人
  message.setfrom(new internetaddress(from));
  // 设置发送时间
  message.setsentdate(new date());
  // 设置收件人
  message.setrecipients(recipienttype.to, internetaddress.parse(to));
  // 设置html内容为邮件正文,指定mime类型为text/html类型,并指定字符编码为gbk
  message.setcontent("<div style='width: 600px;margin: 0 auto'><h3 style='color:#003e64; text-align:center; '>内燃机注册验证码</h3><p style=''>尊敬的用户您好:</p><p style='text-indent: 2em'>您在注册内燃机账号,此次的验证码是:"+code+",有效期10分钟!如果过期请重新获取。</p><p style='text-align: right; color:#003e64; font-size: 20px;'>中国内燃机学会</p></div>","text/html;charset=utf-8");

  //设置自定义发件人昵称
  string nick="";
  try {
   nick=javax.mail.internet.mimeutility.encodetext("中国内燃机学会");
  } catch (unsupportedencodingexception e) {
   e.printstacktrace();
  }
  message.setfrom(new internetaddress(nick+" <"+from+">"));
  // 保存并生成最终的邮件内容
  message.savechanges();

  // 发送邮件
  try {
   transport.send(message);
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }

 }

 /**
  * 发送带内嵌图片的html邮件
  */
 public static void sendhtmlwithinnerimageemail() throws messagingexception {
  // 创建session实例对象
  session session = session.getdefaultinstance(props, new myauthenticator());

  // 创建邮件内容
  mimemessage message = new mimemessage(session);
  // 邮件主题,并指定编码格式
  message.setsubject("带内嵌图片的html邮件", "utf-8");
  // 发件人
  message.setfrom(new internetaddress(from));
  // 收件人
  message.setrecipients(recipienttype.to, internetaddress.parse(to));
  // 抄送
  message.setrecipient(recipienttype.cc, new internetaddress("java_test@sohu.com"));
  // 密送 (不会在邮件收件人名单中显示出来)
  message.setrecipient(recipienttype.bcc, new internetaddress("417067629@qq.com"));
  // 发送时间
  message.setsentdate(new date());

  // 创建一个mime子类型为“related”的mimemultipart对象
  mimemultipart mp = new mimemultipart("related");
  // 创建一个表示正文的mimebodypart对象,并将它加入到前面创建的mimemultipart对象中
  mimebodypart htmlpart = new mimebodypart();
  mp.addbodypart(htmlpart);
  // 创建一个表示图片资源的mimebodypart对象,将将它加入到前面创建的mimemultipart对象中
  mimebodypart imagepart = new mimebodypart();
  mp.addbodypart(imagepart);

  // 将mimemultipart对象设置为整个邮件的内容
  message.setcontent(mp);

  // 设置内嵌图片邮件体
  datasource ds = new filedatasource(new file("resource/firefoxlogo.png"));
  datahandler dh = new datahandler(ds);
  imagepart.setdatahandler(dh);
  imagepart.setcontentid("firefoxlogo.png"); // 设置内容编号,用于其它邮件体引用

  // 创建一个mime子类型为"alternative"的mimemultipart对象,并作为前面创建的htmlpart对象的邮件内容
  mimemultipart htmlmultipart = new mimemultipart("alternative");
  // 创建一个表示html正文的mimebodypart对象
  mimebodypart htmlbodypart = new mimebodypart();
  // 其中cid=androidlogo.gif是引用邮件内部的图片,即imagepart.setcontentid("androidlogo.gif");方法所保存的图片
  htmlbodypart.setcontent("<span style='color:red;'>这是带内嵌图片的html邮件哦!!!<img src=\"cid:firefoxlogo.png\" /></span>","text/html;charset=utf-8");
  htmlmultipart.addbodypart(htmlbodypart);
  htmlpart.setcontent(htmlmultipart);

  // 保存并生成最终的邮件内容
  message.savechanges();

  // 发送邮件
  transport.send(message);
 }

 /**
  * 发送带内嵌图片、附件、多收件人(显示邮箱姓名)、邮件优先级、阅读回执的完整的html邮件
  */
 public static void sendmultipleemail() throws exception {
  string charset = "utf-8"; // 指定中文编码格式
  // 创建session实例对象
  session session = session.getinstance(props,new myauthenticator());

  // 创建mimemessage实例对象
  mimemessage message = new mimemessage(session);
  // 设置主题
  message.setsubject("使用javamail发送混合组合类型的邮件测试");
  // 设置发送人
  message.setfrom(new internetaddress(from,"新浪测试邮箱",charset));
  // 设置收件人
  message.setrecipients(recipienttype.to,
    new address[] {
      // 参数1:邮箱地址,参数2:姓名(在客户端收件只显示姓名,而不显示邮件地址),参数3:姓名中文字符串编码
      new internetaddress("java_test@sohu.com", "张三_sohu", charset),
      new internetaddress("xyang0917@163.com", "李四_163", charset),
    }
  );
  // 设置抄送
  message.setrecipient(recipienttype.cc, new internetaddress("xyang0917@gmail.com","王五_gmail",charset));
  // 设置密送
  message.setrecipient(recipienttype.bcc, new internetaddress("xyang0917@qq.com", "赵六_qq", charset));
  // 设置发送时间
  message.setsentdate(new date());
  // 设置回复人(收件人回复此邮件时,默认收件人)
  message.setreplyto(internetaddress.parse("\"" + mimeutility.encodetext("田七") + "\" <417067629@qq.com>"));
  // 设置优先级(1:紧急 3:普通 5:低)
  message.setheader("x-priority", "1");
  // 要求阅读回执(收件人阅读邮件时会提示回复发件人,表明邮件已收到,并已阅读)
  message.setheader("disposition-notification-to", from);

  // 创建一个mime子类型为"mixed"的mimemultipart对象,表示这是一封混合组合类型的邮件
  mimemultipart mailcontent = new mimemultipart("mixed");
  message.setcontent(mailcontent);

  // 附件
  mimebodypart attach1 = new mimebodypart();
  mimebodypart attach2 = new mimebodypart();
  // 内容
  mimebodypart mailbody = new mimebodypart();

  // 将附件和内容添加到邮件当中
  mailcontent.addbodypart(attach1);
  mailcontent.addbodypart(attach2);
  mailcontent.addbodypart(mailbody);

  // 附件1(利用jaf框架读取数据源生成邮件体)
  datasource ds1 = new filedatasource("resource/earth.bmp");
  datahandler dh1 = new datahandler(ds1);
  attach1.setfilename(mimeutility.encodetext("earth.bmp"));
  attach1.setdatahandler(dh1);

  // 附件2
  datasource ds2 = new filedatasource("resource/如何学好c语言.txt");
  datahandler dh2 = new datahandler(ds2);
  attach2.setdatahandler(dh2);
  attach2.setfilename(mimeutility.encodetext("如何学好c语言.txt"));

  // 邮件正文(内嵌图片+html文本)
  mimemultipart body = new mimemultipart("related"); //邮件正文也是一个组合体,需要指明组合关系
  mailbody.setcontent(body);

  // 邮件正文由html和图片构成
  mimebodypart imgpart = new mimebodypart();
  mimebodypart htmlpart = new mimebodypart();
  body.addbodypart(imgpart);
  body.addbodypart(htmlpart);

  // 正文图片
  datasource ds3 = new filedatasource("resource/firefoxlogo.png");
  datahandler dh3 = new datahandler(ds3);
  imgpart.setdatahandler(dh3);
  imgpart.setcontentid("firefoxlogo.png");

  // html邮件内容
  mimemultipart htmlmultipart = new mimemultipart("alternative");
  htmlpart.setcontent(htmlmultipart);
  mimebodypart htmlcontent = new mimebodypart();
  htmlcontent.setcontent(
    "<span style='color:red'>这是我自己用java mail发送的邮件哦!" +
      "<img src='cid:firefoxlogo.png' /></span>"
    , "text/html;charset=gbk");
  htmlmultipart.addbodypart(htmlcontent);

  // 保存邮件内容修改
  message.savechanges();

  /*file eml = buildemlfile(message);
  sendmailforeml(eml);*/

  // 发送邮件
  transport.send(message);
 }

 /**
  * 将邮件内容生成eml文件
  * @param message 邮件内容
  */
 public static file buildemlfile(message message) throws messagingexception, filenotfoundexception, ioexception {
  file file = new file("c:\\" + mimeutility.decodetext(message.getsubject())+".eml");
  message.writeto(new fileoutputstream(file));
  return file;
 }

 /**
  * 发送本地已经生成好的email文件
  */
 public static void sendmailforeml(file eml) throws exception {
  // 获得邮件会话
  session session = session.getinstance(props,new myauthenticator());
  // 获得邮件内容,即发生前生成的eml文件
  inputstream is = new fileinputstream(eml);
  mimemessage message = new mimemessage(session,is);
  //发送邮件
  transport.send(message);
 }

 /**
  * 向邮件服务器提交认证信息
  */
 static class myauthenticator extends authenticator {

  private string username = "";

  private string password = "";

  public myauthenticator() {
   super();
   this.password=senduserpwd;
   this.username=sendusername;
  }

  public myauthenticator(string username, string password) {
   super();
   this.username = username;
   this.password = password;
  }

  @override
  protected passwordauthentication getpasswordauthentication() {

   return new passwordauthentication(username, password);
  }
 }
}

demo2代码事例:

package com.justin.framework.core.utils.email;

import java.util.hashset;
import java.util.properties;
import java.util.set;
import javax.activation.datahandler;
import javax.activation.filedatasource;
import javax.mail.address;
import javax.mail.bodypart;
import javax.mail.message;
import javax.mail.multipart;
import javax.mail.session;
import javax.mail.transport;
import javax.mail.internet.internetaddress;
import javax.mail.internet.mimebodypart;
import javax.mail.internet.mimemessage;
import javax.mail.internet.mimemultipart;
import javax.mail.internet.mimeutility;

public class mailmanagerutils {
 //发送邮件
 public static boolean sendmail(email email) {
  string subject = email.getsubject();
  string content = email.getcontent();
  string[] recievers = email.getrecievers();
  string[] copyto = email.getcopyto();
  string attbody = email.getattbody();
  string[] attbodys = email.getattbodys();
  if(recievers == null || recievers.length <=0) {
   return false;
  }
  try {
   properties props =new properties();
   props.setproperty("mail.enable", "true");
   props.setproperty("mail.protocal", "smtp");
   props.setproperty("mail.smtp.auth", "true");
   props.setproperty("mail.user", "tdbjrcrm@tdb.com");
   props.setproperty("mail.pass", "new***");
   props.setproperty("mail.smtp.host","mail.tdb.com");

   props.setproperty("mail.smtp.from","tdbjrcrm@tdb.com");
   props.setproperty("mail.smtp.fromname","tdbvc");

   // 创建一个程序与邮件服务器的通信
   session mailconnection = session.getinstance(props, null);
   message msg = new mimemessage(mailconnection);

   // 设置发送人和接受人
   address sender = new internetaddress(props.getproperty("mail.smtp.from"));
   // 多个接收人
   msg.setfrom(sender);

   set<internetaddress> touserset = new hashset<internetaddress>();
   // 邮箱有效性较验
   for (int i = 0; i < recievers.length; i++) {
    if (recievers[i].trim().matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)+$")) {
     touserset.add(new internetaddress(recievers[i].trim()));
    }
   }
   msg.setrecipients(message.recipienttype.to, touserset.toarray(new internetaddress[0]));
   // 设置抄送
   if (copyto != null) {
    set<internetaddress> copytouserset = new hashset<internetaddress>();
    // 邮箱有效性较验
    for (int i = 0; i < copyto.length; i++) {
     if (copyto[i].trim().matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)+$")) {
      copytouserset.add(new internetaddress(copyto[i].trim()));
     }
    }
    // msg.setrecipients(message.recipienttype.cc,(address[])internetaddress.parse(copyto));
    msg.setrecipients(message.recipienttype.cc, copytouserset.toarray(new internetaddress[0]));
   }
   // 设置邮件主题
   msg.setsubject(mimeutility.encodetext(subject, "utf-8", "b")); // 中文乱码问题

   // 设置邮件内容
   bodypart messagebodypart = new mimebodypart();
   messagebodypart.setcontent(content, "text/html; charset=utf-8"); // 中文
   multipart multipart = new mimemultipart();
   multipart.addbodypart(messagebodypart);
   msg.setcontent(multipart);

   /********************** 发送附件 ************************/
   if (attbody != null) {
    string[] filepath = attbody.split(";");
    for (string filepath : filepath) {
     //设置信件的附件(用本地机上的文件作为附件)
     bodypart mdp = new mimebodypart();
     filedatasource fds = new filedatasource(filepath);
     datahandler dh = new datahandler(fds);
     mdp.setfilename(mimeutility.encodetext(fds.getname()));
     mdp.setdatahandler(dh);
     multipart.addbodypart(mdp);
    }
    //把mtp作为消息对象的内容
    msg.setcontent(multipart);
   };
   if (attbodys != null) {
    for (string filepath : attbodys) {
     //设置信件的附件(用本地机上的文件作为附件)
     bodypart mdp = new mimebodypart();
     filedatasource fds = new filedatasource(filepath);
     datahandler dh = new datahandler(fds);
     mdp.setfilename(mimeutility.encodetext(fds.getname()));
     mdp.setdatahandler(dh);
     multipart.addbodypart(mdp);
    }
    //把mtp作为消息对象的内容
    msg.setcontent(multipart);
   }
   ;
   /********************** 发送附件结束 ************************/

   // 先进行存储邮件
   msg.savechanges();
   system.out.println("正在发送邮件....");
   transport trans = mailconnection.gettransport(props.getproperty("mail.protocal"));
   // 邮件服务器名,用户名,密码
   trans.connect(props.getproperty("mail.smtp.host"), props.getproperty("mail.user"), props.getproperty("mail.pass"));
   trans.sendmessage(msg, msg.getallrecipients());
   system.out.println("发送邮件成功!");

   // 关闭通道
   if (trans.isconnected()) {
    trans.close();
   }
   return true;
  } catch (exception e) {
   system.err.println("邮件发送失败!" + e);
   return false;
  } finally {
  }
 }

 // 发信人,收信人,回执人邮件中有中文处理乱码,res为获取的地址
 // http默认的编码方式为iso8859_1
 // 对含有中文的发送地址,使用mimeutility.decodetex方法
 // 对其他则把地址从iso8859_1编码转换成gbk编码
 public static string getchinesefrom(string res) {
  string from = res;
  try {
   if (from.startswith("=?gb") || from.startswith("=?gb") || from.startswith("=?utf")) {
    from = mimeutility.decodetext(from);
   } else {
    from = new string(from.getbytes("iso8859_1"), "gbk");
   }
  } catch (exception e) {
   e.printstacktrace();
  }
  return from;
 }

 // 转换为gbk编码
 public static string tochinese(string strvalue) {
  try {
   if (strvalue == null)
    return null;
   else {
    strvalue = new string(strvalue.getbytes("iso8859_1"), "gbk");
    return strvalue;
   }
  } catch (exception e) {
   return null;
  }
 }

 public static void main(string[] args) {
  email email=new email();
  email.setrecievers(new string[]{"db_yangruirui@tdbcwgs.com"});
  email.setsubject("test测件");
  email.setcontent("test测试");
  sendmail(email);
 }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网