Java Web stmp发送带附件邮件(附SSL版)

 更新时间:2018年05月23日 08:37:29   作者:luck-cheng  
这篇文章主要为大家详细介绍了Java Web stmp发送带附件邮件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Java Web stmp发送带附件邮件的具体代码,供大家参考,具体内容如下

public class MailFileSendUtils {

 private Properties props; //系统属性
 private Session session; //邮件会话对象
 private MimeMessage mimeMsg; //MIME邮件对象
 private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象

 /**
  * Constructor
  * @param
  */
 public MailFileSendUtils(){
  props = System.getProperties();
  props.put("mail.smtp.auth","false");
  session = Session.getDefaultInstance(props, null);
  session.setDebug(true);
  mimeMsg = new MimeMessage(session);
  mp = new MimeMultipart();
 }

 /**
  * Constructor
  * @param smtp 邮件发送服务器
  */
 public MailFileSendUtils(String smtp, String username, String password){
  props = System.getProperties();
  props.put("mail.smtp.auth","true");
  props.put("mail.smtp.host", smtp);
  props.put("username", username);
  props.put("password", password);
  session = Session.getDefaultInstance(props, null);
  session.setDebug(true);
  mimeMsg = new MimeMessage(session);
  mp = new MimeMultipart();
 }

 /**
  * 发送邮件
  */
 public boolean sendMail(String from, String[] to, String subject, String content, String filename) {
  try {
   //设置发信人
   mimeMsg.setFrom(new InternetAddress(from));
   //设置接收人
   for (int i = 0; i < to.length; i++) {
    mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to[i]));
   }
   //设置抄送人
//   for (int i = 0; i < copyto.length; i++) {
//    mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(copyto[i]));
//   }
   //设置主题
   mimeMsg.setSubject(subject);
   //设置正文
   BodyPart bp = new MimeBodyPart();
   bp.setContent(content, "text/html;charset=utf-8");
   mp.addBodyPart(bp);
   //设置附件
   bp = new MimeBodyPart();
   FileDataSource fileds = new FileDataSource(filename);
   bp.setDataHandler(new DataHandler(fileds));
   bp.setFileName(MimeUtility.encodeText(fileds.getName(),"UTF-8","B"));
   mp.addBodyPart(bp);
   mimeMsg.setContent(mp);
   mimeMsg.saveChanges();
   //发送邮件
   if(props.get("mail.smtp.auth").equals("true")){
    Transport transport = session.getTransport("smtp");
    transport.connect((String)props.get("mail.smtp.host"), (String)props.get("username"), (String)props.get("password"));
    transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
//    transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
    transport.close();
   }else{
    Transport.send(mimeMsg);
   }
   System.out.println("邮件发送成功");
  } catch (MessagingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return true;
 }

// public void toSendMail(SendMailParam sendMailParam){
//  MailFileSendUtils email = new MailFileSendUtils(sendMailParam.getSmtp(), sendMailParam.getUsername(), sendMailParam.getPassword());
//  email.sendMail(sendMailParam.getFrom(), sendMailParam.getTo(), sendMailParam.getSubject(), sendMailParam.getContent(), sendMailParam.getFilepath());
// }


 public static void main(String[] args) {
  String smtp = "smtp.exmail.qq.com";
  String username = "发送的邮箱账号";
  String password = "发送的邮箱密码";
  String from = "发送的邮箱";
  String[] to = {"接收邮件的邮箱"};
//  String[] copyto = {"抄送的邮箱"};
  String subject = "主题6";
  String content = "邮件内容6";
  String filename = "附件的文件";
  MailFileSendUtils email = new MailFileSendUtils(smtp, username, password);
//  email.sendMail(from, to, copyto, subject, content, filename);
  email.sendMail(from, to, subject, content, filename);
 }

}

(附:SSL版)

public class MailFileSendUtils {

 private Properties props; //系统属性
 private Session session; //邮件会话对象
 private MimeMessage mimeMsg; //MIME邮件对象
 private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象

 /**
  * Constructor
  * @param
  */
 public MailFileSendUtils(){
  props = System.getProperties();
  props.put("mail.smtp.auth","false");
  session = Session.getDefaultInstance(props, null);
  session.setDebug(true);
  mimeMsg = new MimeMessage(session);
  mp = new MimeMultipart();
 }

 /**
  * Constructor
  * @param smtp 邮件发送服务器
  */
 public MailFileSendUtils(String smtp,
        String username,
        String password){
  Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
  props = System.getProperties();
  MailSSLSocketFactory sf = null;
  try {
   sf = new MailSSLSocketFactory();
  } catch (GeneralSecurityException e) {
  }
  sf.setTrustAllHosts(true);
  props.put("mail.smtp.auth","true");
  props.put("mail.smtp.host", smtp);
  props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
  props.put("mail.smtp.socketFactory.fallback", "false");
  props.put("mail.smtp.ssl.enable", "true");
  props.put("mail.smtp.port", "465");
  props.put("mail.smtp.ssl.socketFactory", sf);

//  props.put("username", username);
//  props.put("password", password);
  session = Session.getInstance(props, new Authenticator() {
   @Override
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username, password);
   }
  });
  session.setDebug(true);
  mimeMsg = new MimeMessage(session);
  mp = new MimeMultipart();
 }

 /**
  * 发送邮件
  */
 public boolean sendMail(String from,
       String[] to,
       String subject,
       String content,
       String filename) {
  try {
   //设置发信人
   mimeMsg.setFrom(new InternetAddress(from));
   //设置接收人
   for (int i = 0; i < to.length; i++) {
    mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to[i]));
   }
   //设置抄送人
//   for (int i = 0; i < copyto.length; i++) {
//    mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(copyto[i]));
//   }
   //设置主题
   mimeMsg.setSubject(subject);
   //设置正文
   BodyPart bp = new MimeBodyPart();
   bp.setContent(content, "text/html;charset=utf-8");
   mp.addBodyPart(bp);
   //设置附件
   bp = new MimeBodyPart();
   FileDataSource fileds = new FileDataSource(filename);
   bp.setDataHandler(new DataHandler(fileds));
   bp.setFileName(MimeUtility.encodeText(fileds.getName(),"UTF-8","B"));
   mp.addBodyPart(bp);
   mimeMsg.setContent(mp);
   mimeMsg.saveChanges();
   //发送邮件
   if(props.get("mail.smtp.auth").equals("true")){
    Transport transport = session.getTransport("smtp");
    transport.connect((String)props.get("mail.smtp.host"), (String)props.get("username"), (String)props.get("password"));
    transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
//    transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
    transport.close();
   }else{
    Transport.send(mimeMsg);
   }
   System.out.println("邮件发送成功");
  } catch (MessagingException e) {
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }
  return true;
 }

 public boolean toSendMail(SendMailParam sendMailParam){
  MailFileSendUtils email = new MailFileSendUtils(
    sendMailParam.getSmtp(),
    sendMailParam.getUsername(),
    sendMailParam.getPassword());
  email.sendMail(
    sendMailParam.getFrom(),
    sendMailParam.getTo(),
    sendMailParam.getSubject(),
    sendMailParam.getContent(),
    sendMailParam.getFilepath());
  return true;
 }


// public static void main(String[] args) {
//  String smtp = "smtp.mxhichina.com";
//  String username = "邮箱";
//  String password = "邮箱密码";
//  String from = "谁去发";
//  String[] to = {"发给谁"};
////  String[] copyto = {"抄送的邮箱"};
//  String subject = "huawei";
//  String content = "邮件内容6666";
//  String filename = "gdt-3583118353-ad-20170823.xls";
//  MailFileSendUtils email = new MailFileSendUtils(smtp, username, password);
////  email.sendMail(from, to, copyto, subject, content, filename);
//  email.sendMail(from, to, subject, content, filename);
// }

}

在项目中使用这套工具,main方法我注释掉,然后使用toSendMail(SendMailParam sendMailParam)。
这里定义的SendMailParam 为:

public class SendMailParam {
 private String smtp;
 private String username;
 private String password;
 private String from;//发送人
 private String[] to;//接收人
 //  String[] copyto = {"909891736@qq.com"};
 private String subject;//邮件主题
 private String content;//邮件内容
 private String filepath;//文件拿到的路径

 public SendMailParam(){
  this.smtp = "smtp.exmail.qq.com";//例子
  this.username = "邮箱账号";
  this.password = "邮箱密码";
  this.from = "邮箱";
  this.subject = "";
  this.content = "";
  this.filepath = "";
 }

 public String getSmtp() {
  return smtp;
 }

 public void setSmtp(String smtp) {
  this.smtp = smtp;
 }

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getFrom() {
  return from;
 }

 public void setFrom(String from) {
  this.from = from;
 }

 public String[] getTo() {
  return to;
 }

 public void setTo(String[] to) {
  this.to = to;
 }

 public String getSubject() {
  return subject;
 }

 public void setSubject(String subject) {
  this.subject = subject;
 }

 public String getContent() {
  return content;
 }

 public void setContent(String content) {
  this.content = content;
 }

 public String getFilepath() {
  return filepath;
 }

 public void setFilepath(String filepath) {
  this.filepath = filepath;
 }
}

maven依赖包

<dependency>
  <groupId>javax.mail</groupId>
  <artifactId>mail</artifactId>
  <version>1.4.7</version>
 </dependency>

gradle依赖包

compile "javax.mail:mail:1.4.7"

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

相关文章

  • springboot中spring.profiles.include的妙用分享

    springboot中spring.profiles.include的妙用分享

    这篇文章主要介绍了springboot中spring.profiles.include的妙用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • idea导入项目框架的详细操作方法

    idea导入项目框架的详细操作方法

    大家使用idea开发工具时经常会需要导入项目框架,纠结该怎么操作呢,今天小编给大家分享一篇图文教程,帮助大家解决idea导入项目框架的问题,感兴趣的朋友一起看看吧
    2021-05-05
  • 2021年最新Redis面试题汇总(1)

    2021年最新Redis面试题汇总(1)

    在程序员面试过程中redis相关的知识是常被问到的话题。这篇文章主要介绍了几道Redis面试题,整理一下分享给大家,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • java虚拟机钩子关闭函数addShutdownHook的操作

    java虚拟机钩子关闭函数addShutdownHook的操作

    这篇文章主要介绍了java虚拟机钩子关闭函数addShutdownHook的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • Mybatis-Plus同时使用逻辑删除和唯一索引的问题及解决办法(报数据重复Duplicate entry的问题)

    Mybatis-Plus同时使用逻辑删除和唯一索引的问题及解决办法(报数据重复Duplicate entry的

    在开发中,我们经常会有逻辑删除和唯一索引同时使用的情况,但当使用mybatis plus时,如果同时使用逻辑删除和唯一索引,会报数据重复Duplicate entry的问题,如何解决这个问题呢,小编给大家分享Mybatis-Plus同时使用逻辑删除和唯一索引的问题及解决办法,一起看看吧
    2023-11-11
  • Java轻松实现在Excel中添加超链接功能

    Java轻松实现在Excel中添加超链接功能

    这篇文章主要为大家详细介绍了Java如何轻松实现在Excel中添加超链接功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-01-01
  • 浅谈java安全编码指南之堆污染

    浅谈java安全编码指南之堆污染

    什么是堆污染呢?是指当参数化类型变量引用的对象不是该参数化类型的对象时而发生的。我们知道在JDK5中,引入了泛型的概念,在创建集合类的时候,指定该集合类中应该存储的对象类型。如果在指定类型的集合中,引用了不同的类型,那么这种情况就叫做堆污染。
    2021-06-06
  • SpringBoot集成Kafka 配置工具类的详细代码

    SpringBoot集成Kafka 配置工具类的详细代码

    spring-kafka 是基于 java版的 kafka client与spring的集成,提供了 KafkaTemplate,封装了各种方法,方便操作,它封装了apache的kafka-client,不需要再导入client依赖,这篇文章主要介绍了SpringBoot集成Kafka 配置工具类,需要的朋友可以参考下
    2022-09-09
  • SpringBoot结合JSR303对前端数据进行校验的示例代码

    SpringBoot结合JSR303对前端数据进行校验的示例代码

    这篇文章主要介绍了SpringBoot结合JSR303对前端数据进行校验的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Java Spring 事件监听详情解析

    Java Spring 事件监听详情解析

    这篇文章主要介绍了Java Spring 事件监听详情解析,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-07-07

最新评论