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

简介: public class MailFileSendUtils { private Properties props; //系统属性 private Session session; //邮件会话对象 ...
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"
目录
相关文章
|
4月前
|
SQL 监控 安全
Java Web应用的安全防护与攻防策略
Java Web应用的安全防护与攻防策略
|
21天前
|
Java 网络安全 Maven
Exception in thread "main" java.lang.NoSuchMethodError: okhttp3.OkHttpClient$Builder.sslSocketFactory(Ljavax/net/ssl/SSLSocketFactory;Ljavax/net/ssl/X509TrustManager;)Lokhttp3/OkHttpClient$Builder; 问题处理
【10月更文挑战第26天】Exception in thread "main" java.lang.NoSuchMethodError: okhttp3.OkHttpClient$Builder.sslSocketFactory(Ljavax/net/ssl/SSLSocketFactory;Ljavax/net/ssl/X509TrustManager;)Lokhttp3/OkHttpClient$Builder; 问题处理
37 2
|
1月前
|
JavaScript 安全 Java
谈谈UDP、HTTP、SSL、TLS协议在java中的实际应用
下面我将详细介绍UDP、HTTP、SSL、TLS协议及其工作原理,并提供Java代码示例(由于Deno是一个基于Node.js的运行时,Java代码无法直接在Deno中运行,但可以通过理解Java示例来类比Deno中的实现)。
71 1
|
3月前
|
算法 Java 测试技术
java 访问ingress https报错javax.net.ssl.SSLHandshakeException: Received fatal alert: protocol_version
java 访问ingress https报错javax.net.ssl.SSLHandshakeException: Received fatal alert: protocol_version
|
3月前
|
安全 Java 关系型数据库
Java连接Mysql SSL初始化失败
Java连接Mysql SSL初始化失败
|
3月前
|
安全 前端开发 Java
Web端系统开发解决跨域问题——以Java SpringBoot框架配置Cors为例
在Web安全上下文中,源(Origin)是指一个URL的协议、域名和端口号的组合。这三个部分共同定义了资源的来源,浏览器会根据这些信息来判断两个资源是否属于同一源。例如,https://www.example.com:443和http://www.example.com虽然域名相同,但由于协议和端口号不同,它们被视为不同的源。同源(Same-Origin)是指两个URL的协议、域名和端口号完全相同。只有当这些条件都满足时,浏览器才认为这两个资源来自同一源,从而允许它们之间的交互操作。
Web端系统开发解决跨域问题——以Java SpringBoot框架配置Cors为例
|
3月前
|
Java Maven Android开发
解锁Web开发新技能:从零开始的Struts 2之旅——让你的Java编程之路更加宽广,首个应用实例带你飞!
【8月更文挑战第31天】对于初学者,掌握 Struts 2 框架不仅能提升 Web 开发能力,还能深入了解 MVC 架构。Struts 2 是一个基于 Servlet 的 Java 框架,提供表单验证、文件上传、国际化等功能,便于快速构建易维护的 Web 应用。本文通过示例演示如何从零开始搭建环境并创建一个简单的 Struts 2 项目,包括配置 `struts.xml`、编写 Action 类及视图文件,并配置 web.xml。通过这些步骤,你将学会基本的开发流程,为进一步学习高级功能打下基础。
50 0
|
4月前
|
消息中间件 Java 微服务
构建可扩展的Java Web应用架构
构建可扩展的Java Web应用架构
|
4月前
|
Java UED
Java Web 中forward 和 redirect 的区别
在Java Web开发中,页面跳转是构建用户界面和实现业务逻辑的重要组成部分。Forward(转发)和Redirect(重定向)是两种常见的跳转方式,它们分别具有不同的特点和适用场景。正确地选择和使用这两种跳转方式,有助于提高Web应用的性能、用户体验和代码可维护性。
71 0
|
5月前
|
存储 Java 关系型数据库
基于Servlet和JSP的Java Web应用开发指南
【6月更文挑战第23天】构建Java Web应用,Servlet与JSP携手打造在线图书管理系统,涵盖需求分析、设计、编码到测试。通过实例展示了Servlet如何处理用户登录(如`LoginServlet`),JSP负责页面展示(如`login.jsp`和`bookList.jsp`)。应用基于MySQL数据库,包含用户和图书表。登录失败显示错误信息,成功后展示图书列表。部署到Tomcat服务器测试功能。此基础教程为深入Java Web开发奠定了基础。
113 10

热门文章

最新文章