当前位置: 移动技术网 > IT编程>开发语言>Java > 使用spring框架中的组件发送邮件功能说明

使用spring框架中的组件发送邮件功能说明

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

spring框架是由于软件开发的复杂性而创建的。spring使用的是基本的javabean来完成以前只可能由ejb完成的事情。然而,spring的用途不仅仅限于服务器端的开发。从简单性、可测试性和松耦合性角度而言,绝大部分java应用都可以从spring中受益。

首先进入自己的qq邮箱,在设置中修改账户信息

然后来至底部

点击开启,再用手机发送对应信息到指定号码,然后点击我已发送

获取授权码

注意提示:

到这里,相信你已经开通了smtp服务,这样就可以在java code发送邮件了

接下来的是spring 中使用邮件服务

首先是配置信息使用的是587端口,刚开始用465端口我纠结了好久(使用465端口的错误详情),用不了,你可以尝试,默认的25端口应该也是不适合的

<!-- 邮件服务 -->
  <bean id="mailsender" class="org.springframework.mail.javamail.javamailsenderimpl">
    <property name="host" value="smtp.qq.com"/>
    <property name="port" value="587"/>//或许你可以用465端口,默认的25不适合
    <property name="protocol" value="smtp"/>
    <property name="username" value="785427346@qq.com"/>
    <property name="password" value="xxxxxxxxxxxx"/>//这里的是你通过短信后,获取的授权码
    <property name="defaultencoding" value="utf-8"/>
    <property name="javamailproperties"> 
      <props> 
        <prop key="mail.smtp.auth">true</prop> 
        <prop key="mail.smtp.timeout">25000</prop> 
      </props> 
    </property> 
  </bean>
  <!-- this is a template message that we can pre-load with default state -->
  <bean id="templatemessage" class="org.springframework.mail.simplemailmessage">
    <property name="from" value="785427346@qq.com"/>
    <property name="subject" value="尝试发邮件"/>
  </bean>
  <bean id="ordermanager" class="cn.cherish.common.simpleordermanager">
    <property name="mailsender" ref="mailsender"/>
    <property name="templatemessage" ref="templatemessage"/>
  </bean>

用maven引入的jar包

 <!-- 邮件 -->
  <dependency>
    <groupid>org.springframework</groupid>
    <artifactid>spring-context-support</artifactid>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupid>javax.mail</groupid>
    <artifactid>mail</artifactid>
    <version>1.4.7</version>
  </dependency>

下面只是一个工具类作简单例子,请勿见怪

package cn.cherish.common;
import java.io.bufferedreader;
import java.io.file;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.net.url;
import java.net.urlconnection;
import java.util.properties;
import javax.mail.messagingexception;
import javax.mail.internet.mimemessage;
import org.springframework.core.io.filesystemresource;
import org.springframework.mail.mailexception;
import org.springframework.mail.simplemailmessage;
import org.springframework.mail.javamail.javamailsenderimpl;
import org.springframework.mail.javamail.mimemessagehelper;
/**
 * 项目名称:springmvc_hibernate
 * 类名称:mailutil
 * 类描述:
 * 创建人:cherish
 * 联系方式:785427346@qq.com
 * 创建时间:2016年4月22日 下午3:51:48
 * @version 1.0
 */
public class mailutil {
  private static final string host = "smtp.qq.com";
  private static final string smtp = "smtp";
  private static final string username = "785427346@qq.com";
  private static final string password = "xxxxxxxxxx";
  private static final int port = 587;//587/465
  private static final string defaultencoding = "utf-8";
  private static javamailsenderimpl senderimpl = new javamailsenderimpl();
  private static properties prop = new properties();
  static{
    // 设定mail server
    senderimpl.sethost(host);
    senderimpl.setprotocol(smtp);
    senderimpl.setusername(username);
    senderimpl.setpassword(password);
    senderimpl.setport(port);
    senderimpl.setdefaultencoding(defaultencoding);
    // 设定properties
    prop.put("mail.smtp.auth", "true");
    prop.put("mail.smtp.timeout", "25000");
    //设置调试模式可以在控制台查看发送过程
    prop.put("mail.debug", "true");
    senderimpl.setjavamailproperties(prop);
  }
  public static void main(string args[]) {
    // 设置收件人,寄件人 用数组发送多个邮件
//   string[] array = new string[] {"88888@qq.com","666666@qq.com","999999999@qq.com",username};
    string[] array = new string[] {username};
    string subject = "cherish内嵌图片、音乐的邮件";
//   stringbuffer sb = new stringbuffer();
//   try {
//     url url = new url("http://www.imooc.com/");//http://android-studio.org/
//     
//     urlconnection conn = url.openconnection();
//     inputstream is = conn.getinputstream();
//     
//     bufferedreader reader = new bufferedreader(new inputstreamreader(is));
//     
//     string string = null;
//     while ((string = reader.readline()) != null) {
//       sb.append(string);
//     }
//     
//     //system.out.println(sb.tostring());
//     
//   } catch (exception e) {
//     e.printstacktrace();
//   }
//   
//   boolean result = htmlmail(array, subject, sb.tostring());
    string filepath = "e:/javaxmail.png";
    string html = "<html><head>"+
          "</head><body>"+
          "<audio src='http://m10.music.126.net/20160422225433/25b43b999bcdaf3425b9194514340596/ymusic/8c94/b9af/69e3/7ebe35b8e00154120822550b21b0c9c5.mp3' autoplay='autoplay' controls='controls' loop='-1'>爱你</audio>"+
          "<h1>hello,nice to meet you!</h1>"+
          "<span style='color:red;font-size:36px;'>并摸了一把你的小奶</span>"+
          "<img src='cid:javaxmail.png'>"+
          "</body></html>";
    boolean result = inlinefilemail(array, subject, html, filepath);
    if (result) {
      system.out.println("发送邮件成功。。。。");
    }
  }
  /**
   * 发送简单邮件
   * @param to 收件人邮箱
   * @param subject 主题
   * @param content 内容
   * @return
   */
  public static boolean singlemail(string to, string subject, string content){
    string[] array = new string[] {to};
    return singlemail(array, subject, content);
  }
  /**
   * 发送简单文本邮件
   * @param to 收件人邮箱数组
   * @param subject 主题
   * @param content 内容
   * @return
   */
  public static boolean singlemail(string[] to, string subject, string content){
    boolean result = true;
    simplemailmessage mailmessage = new simplemailmessage();
    // 设置收件人,寄件人 用数组发送多个邮件
    mailmessage.setto(to);
    mailmessage.setfrom(username);
    mailmessage.setsubject(subject);
    mailmessage.settext(content);
    // 发送邮件
    try {
      senderimpl.send(mailmessage);
    } catch (mailexception e) {
      e.printstacktrace();
      result = false;
    }
    return result;
  }
  /**
   * 发送html邮件
   * @param to 收件人
   * @param subject 主题
   * @param html html代码
   * @return
   */
  public static boolean htmlmail(string[] to, string subject, string html){
    boolean result = true;
    mimemessage mailmessage = senderimpl.createmimemessage(); 
    mimemessagehelper messagehelper = new mimemessagehelper(mailmessage); 
    try {
      // 设置收件人,寄件人 用数组发送多个邮件
      messagehelper.setto(to);
      messagehelper.setfrom(username);
      messagehelper.setsubject(subject);
      // true 表示启动html格式的邮件 
      messagehelper.settext(html, true); 
      // 发送邮件
      senderimpl.send(mailmessage);
    } catch (messagingexception e) {
      result = false;
      e.printstacktrace();
    }
    return result;
  }
  /**
   * 发送内嵌图片的邮件  (cid:资源名)
   * @param to 收件人邮箱
   * @param subject 主题
   * @param html html代码
   * @param imgpath 图片路径
   * @return
   */
  public static boolean inlinefilemail(string[] to, string subject, string html, string filepath){
    boolean result = true;
    mimemessage mailmessage = senderimpl.createmimemessage(); 
    try {
      //设置true开启嵌入图片的功能
      mimemessagehelper messagehelper = new mimemessagehelper(mailmessage,true); 
      // 设置收件人,寄件人 用数组发送多个邮件
      messagehelper.setto(to);
      messagehelper.setfrom(username);
      messagehelper.setsubject(subject);
      // true 表示启动html格式的邮件 
      messagehelper.settext(html, true); 
      filesystemresource file = new filesystemresource(new file(filepath)); 
      messagehelper.addinline(file.getfilename(), file); 
      // 发送邮件
      senderimpl.send(mailmessage);
    } catch (messagingexception e) {
      result = false;
      e.printstacktrace();
    }
    return result;
  }
  /**
   * 发送带附件的邮件
   * @param to
   * @param subject
   * @param html
   * @param filepath
   * @return
   */
  public static boolean attachedfilemail(string[] to, string subject, string html, string filepath){
    boolean result = true;
    mimemessage mailmessage = senderimpl.createmimemessage(); 
    try {
      // multipart模式 为true时发送附件 可以设置html格式
      mimemessagehelper messagehelper = new mimemessagehelper(mailmessage,true,"utf-8"); 
      // 设置收件人,寄件人 用数组发送多个邮件
      messagehelper.setto(to);
      messagehelper.setfrom(username);
      messagehelper.setsubject(subject);
      // true 表示启动html格式的邮件 
      messagehelper.settext(html, true); 
      filesystemresource file = new filesystemresource(new file(filepath)); 
      // 这里的方法调用和插入图片是不同的。 
      messagehelper.addattachment(file.getfilename(), file);
      // 发送邮件
      senderimpl.send(mailmessage);
    } catch (messagingexception e) {
      result = false;
      e.printstacktrace();
    }
    return result;
  }

温馨提示:

<img src='cid:javaxmail.png'>

这是内嵌图片的方式 javaxmail.png 要和 messagehelper.addinline(file.getfilename(), file); 这里的 file.getfilename() 相一致就可以

现在只差一步了,那就是ctrl + f11,有不当之处敬请提出,共同进步

**
使用javax.mail发邮件代码
**
package cn.cherish.utils;
import java.io.file;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.util.date;
import java.util.properties;
import javax.activation.datahandler;
import javax.activation.datasource;
import javax.activation.filedatasource;
import javax.mail.authenticator;
import javax.mail.bodypart;
import javax.mail.message;
import javax.mail.messagingexception;
import javax.mail.multipart;
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.mimemessage.recipienttype;
import javax.mail.internet.mimemultipart;
import javax.mail.internet.mimeutility;
/**
 * 项目名称:springmvc_hibernate 
 * 类名称:emailutil 
 * 类描述:发送邮件工具类 
 * 创建人:cherish
 * 联系方式:785427346@qq.com 
 * 创建时间:2016年4月23日 上午9:48:21
 * @version 1.0
 */
public class emailutil {
 // properties配置文件地址
 //private static final string properties_path = "standard_data.properties";
 private static session session;
 private static properties props = new properties();
 private static final string host = "smtp.qq.com";
 private static int port = 587;
 private static final string isauth = "true";
 private static final string from = "785427346@qq.com";
 private static final string username = "785427346@qq.com";
 private static final string password = "xxxxxxxxxxxxxxxx";
 private static final string timeout = "25000";
 private static final string debug = "true";
 // 初始化session
 static {
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.port", port);
  props.put("mail.smtp.auth", isauth);
  props.put("fromer", from);
  props.put("username", username);
  props.put("password", password);
  props.put("mail.smtp.timeout", timeout);
  props.put("mail.debug", debug);
  session = session.getinstance(props, new authenticator() {
   @override
   protected passwordauthentication getpasswordauthentication() {
    return new passwordauthentication(username, password);
   }
  });
 }
 public static void main(string[] args) {
  try {
   string html = "<html><head>"+
     "</head><body>"+
     "<audio src='http://219.128.78.22/m10.music.126.net/20160423105749/3cee5688a7dc87d28a265fd992ecb0a2/ymusic/8c94/b9af/69e3/7ebe35b8e00154120822550b21b0c9c5.mp3?wshc_tag=1&wsts_tag=571aded1&wsid_tag=b73f773e&wsiphost=ipdbm' autoplay='autoplay' controls='controls' loop='-1'>爱你</audio>"+
     "<video controls='controls'>"+
     "<source src='http://v2.mukewang.com/45ad4643-87d7-444b-a3b9-fbf32de63811/h.mp4?auth_key=1461379796-0-0-e86cefa71cef963875fd68f8a419dd8a' type='video/mp4' />"+
     "your browser does not support the video tag."+
     "</video>"+
     "<h1>hello,nice to fuck you!</h1>"+
     "<span style='color:red;font-size:36px;'>并抓了一把你的小鸡鸡</span>"+
     "</body></html>";
   //sendemail("785427346@qq.com", "yeah", html, true);
   sendfileemail("785427346@qq.com", "yeah", html, new file("e:/xiaoming.zip"));
  } catch (exception e) {
   e.printstacktrace();
  }
 }
 /**
  * 
  * @title sendemail
  * @description 通过ishtml判断发送的邮件的内容
  * @param to 邮件接收者
  * @param content 邮件内容
  * @param ishtml 是否发送html
  * @throws messagingexception
  * @throws ioexception
  * @throws filenotfoundexception
  * @throws emailexception
  */
 public static void sendemail(string to, string title, string content, boolean ishtml)
   throws filenotfoundexception, ioexception, messagingexception {
  string fromer = props.getproperty("fromer");
  if (ishtml) {
   sendhtmlemail(fromer, to, title, content);
  } else {
   sendtextemail(fromer, to, title, content);
  }
 }
 // 发送纯文字邮件
 public static void sendtextemail(string from, string to, string subject, string content)
   throws filenotfoundexception, ioexception, messagingexception {
  message message = new mimemessage(session);
  message.setfrom(new internetaddress(from));
  message.setrecipient(recipienttype.to, new internetaddress(to));
  message.setsubject(subject);
  message.settext(content);
  message.setsentdate(new date());
  transport.send(message);
 }
 // 发送有html格式邮件
 public static void sendhtmlemail(string from, string to, string subject, string htmlconent)
   throws filenotfoundexception, ioexception, messagingexception {
  message message = new mimemessage(session);
  message.setfrom(new internetaddress(from));
  message.setrecipient(recipienttype.to, new internetaddress(to));
  message.setsubject(subject);
  message.setsentdate(new date());
  multipart multi = new mimemultipart();
  bodypart html = new mimebodypart();
  html.setcontent(htmlconent, "text/html; charset=utf-8");
  multi.addbodypart(html);
  message.setcontent(multi);
  transport.send(message);
 }
 // 发送带附件的邮件
 public static void sendfileemail(string to, string subject, string htmlconent, file attachment)
   throws filenotfoundexception, ioexception, messagingexception {
  message message = new mimemessage(session);
  string fromer = props.getproperty("fromer");
  message.setfrom(new internetaddress(fromer));
  message.setrecipient(recipienttype.to, new internetaddress(to));
  message.setsubject(subject);
  message.setsentdate(new date());
  // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
  multipart multipart = new mimemultipart();
  // 添加邮件正文
  bodypart contentpart = new mimebodypart();
  contentpart.setcontent(htmlconent, "text/html;charset=utf-8");
  multipart.addbodypart(contentpart);
  // 添加附件的内容
  if (attachment != null) {
   bodypart attachmentbodypart = new mimebodypart();
   datasource source = new filedatasource(attachment);
   attachmentbodypart.setdatahandler(new datahandler(source));
   // 网上流传的解决文件名乱码的方法,其实用mimeutility.encodeword就可以很方便的搞定
   // 这里很重要,通过下面的base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
   // sun.misc.base64encoder enc = new sun.misc.base64encoder();
   // messagebodypart.setfilename("=?gbk?b?" +
   // enc.encode(attachment.getname().getbytes()) + "?=");
   // mimeutility.encodeword可以避免文件名乱码
   attachmentbodypart.setfilename(mimeutility.encodeword(attachment.getname()));
   multipart.addbodypart(attachmentbodypart);
  }
  message.setcontent(multipart);
  transport.send(message);
 }
}

总结

以上所述是小编给大家介绍的使用spring框架中的组件发送邮件,希望对大家有所帮助

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

相关文章:

验证码:
移动技术网