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

本文实例为大家分享了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"

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

(0)

相关推荐

  • java开发https请求ssl不受信任问题解决方法

    本文主要讨论的是java开发https请求ssl不受信任的解决方法,具体分析及实现代码如下. 在java代码中请求https链接的时候,可能会报下面这个错误 javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unab

  • Java如何跳过https的ssl证书验证详解

    打开我们首页,明显看到链接是https打头,https和http的通信协议差别,在于https安全性更高: http和https的差别 很明显,二者最大的区别在于https多了一个ssl证书验证,可以说https是身披SSL外壳的http.因为http存在如下缺陷: 1)通信使用明文,内容可能被窃听(重要密码泄露) 2)不验证通信方身份,有可能遭遇伪装(跨站点请求伪造) 3)无法证明报文的完整性,有可能已遭篡改(运营商劫持) 而https是利用SSL/TLS建立全信道,加密数据包.HTTPS使用

  • 使用httpclient无需证书调用https的示例(java调用https)

    使用httpclient无需证书调用https的url地址,传输字节流. 复制代码 代码如下: package com.paic.hmreport.metaQ; import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.FileOutputStream;import java.io.IOException;import ja

  • Java Classloader机制用法代码解析

    做Java开发,对于ClassLoader的机制是必须要熟悉的基础知识,本文针对Java ClassLoader的机制做一个简要的总结.因为不同的JVM的实现不同,本文所描述的内容均只限于Hotspot Jvm. 本文将会从JDK默认的提供的ClassLoader,双亲委托模型,如何自定义ClassLoader以及Java中打破双亲委托机制的场景四个方面入手去讨论和总结一下. JDK默认ClassLoader JDK 默认提供了如下几种ClassLoader Bootstrp loader Bo

  • 纯Java实现数字证书生成签名的简单实例

    package com.ylsoft.cert; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator;

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

    本文实例为大家分享了Java Web stmp发送带附件邮件的具体代码,供大家参考,具体内容如下 public class MailFileSendUtils { private Properties props; //系统属性 private Session session; //邮件会话对象 private MimeMessage mimeMsg; //MIME邮件对象 private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成Mi

  • java中javamail发送带附件的邮件实现方法

    本文实例讲述了java中javamail发送带附件的邮件实现方法.分享给大家供大家参考.具体分析如下: JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口.它是Sun发布的用来处理email的API.它可以方便地执行一些常用的邮件传输,JavaMail是可选包,因此如果需要使用的话你需要首先从java官网上下载.目前最新版本是JavaMail1.5.0,下面我们来看看javamail发送带附件的邮件实例 mail.java 代码: 复制代码 代码如下: package mail;

  • Java实现批量发送带附件的邮件代码

    目录 前言 实体类(注意注释) 实现类 方法中调用,详情如下: 总结 前言 新功能上线时要经常发包到测试或生产服务器进行模块部署,但由于安全限制只能通过邮件传输小于10M的附件这种方式把jar包上传到服务器.所以往往要发送几十个邮件手动发送比较麻烦,偷懒写了个粘贴即用的Demo,如有不足,请多指教! 实体类(注意注释) 代码详情如下: package Email; /* * 参数实体类 * */ public class EmailParameter { //发信邮箱 private Strin

  • php实现的发送带附件邮件类实例

    本文实例讲述了php实现的发送带附件邮件类的方法,是一个非常实用的功能.分享给大家供大家参考.具体方法如下: emailclass.php类文件如下: <? class CMailFile { var $subject; var $addr_to; var $text_body; var $text_encoded; var $mime_headers; var $mime_boundary = "--==================_846811060==_"; var $

  • Python3使用SMTP发送带附件邮件

    一.设置开启SMTP服务并获取授权码 可以参考第一篇文章,这里不再赘述:[一]https://www.jb51.net/article/142220.htm 二.使用Python3 发送带附件的邮件 0.使用的环境为: Python 3.6.3 (64bit) PyCharm 2017.3 (64bit) 1.注意事项: 在调用smtplib,发送简单邮件的时候使用smtplib.SMTP()方法使没有问题的. 但是如果是邮件存在附件的情况下,还使用smtplib.SMTP()方法,就可能会发送

  • python smtplib发送带附件邮件小程序

    最近经常需要出一些临时性的报表,于是就用python 的smtplib 和email 两模块写了个小程序,当数据处理完后通过邮箱把报表文件从服务器上发送出来! 程序名称:sendMail_func.py #!/usr/bin/env python # -*- coding:utf-8 -*- import os import sys import time import smtplib from email import encoders from email.mime.text import

  • php 发送带附件邮件示例

    emailclass.php 复制代码 代码如下: <? class CMailFile { var $subject; var $addr_to; var $text_body; var $text_encoded; var $mime_headers; var $mime_boundary = "--==================_846811060==_"; var $smtp_headers; function CMailFile($subject,$to,$fro

  • smtp发送带附件的邮件代码分享

    该方式直接保存为HTML文件,也可以是文本文件,其它格式效果不是很好 复制代码 代码如下: MailMessage mmsg = new MailMessage();     mmsg.Subject = "邮件标题";     mmsg.Body = "邮件内容";     mmsg.To.Add("accept@qq.com");//接收邮箱     byte[] bytes = System.Text.Encoding.Default.Ge

  • python实现发送带附件的邮件代码分享

    具体代码如下: from django.template import loader from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header import smtplib import traceback class SendEmail(object):     """     发送html邮件    

  • 基于SpringBoot实现发送带附件的邮件

    这篇文章主要介绍了基于SpringBoot实现发送带附件的邮件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 <!--发送email依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependenc

随机推荐