zoukankan      html  css  js  c++  java
  • 使用Apache commons email发送邮件

    今天研究了一下怎么用java代码发送邮件,用的是Apache的commons-email包。

    据说这个包是对javamail进行了封装,简化了操作。 这里讲一下具体用法吧

    一.首先你需要有邮箱账号和一个授权码。

    需要进入到QQ邮箱或者是网易邮箱里面去获取。在邮箱的设置->账户里面,开启如下服务,就能得到一个授权码,这个授权码要好好保管。有了这两个东西就能够通过第三方客户端发送邮件了。

    二.导入commons-email的maven依赖。

    我用的是1.4,也可以去maven仓库网站(https://mvnrepository.com)上面找别的版本。

    <dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-email</artifactId>
         <version>1.4</version>
     </dependency>

    三.然后就可以写发送邮件的代码了。

    我在网上找了几个案例,如下。

     1.发送简单文本邮件。这是最简单也是最常用的。

        /**
         * @describe 发送内容为简单文本的邮件
         * @throws EmailException
         */
        public static void sendSimpleTextEmail() throws EmailException {
             Email email = new SimpleEmail();
             //设置主机名,QQ邮箱是"smtp.qq.com",网易邮箱是"smtp.163.com"
             email.setHostName("smtp.163.com");
             // 用户名和密码为邮箱的账号和授权码(不需要进行base64编码)
             email.setAuthenticator(new DefaultAuthenticator("myemailaddress@163.com", "myshouquanma"));
             //设置SSL连接,这样写就对了
             email.setSSLOnConnect(true);
             //设置来源,就是发送方的邮箱地址
             email.setFrom("myemailaddress@163.com");
             //设置主题,可以不设置
             email.setSubject("java发送邮件");
             //设置信息,就是内容,这个必须要有
             email.setMsg("这是测试邮件 ... :-)");
             //接收人邮箱地址
             email.addTo("receiveeraddress@qq.com");
             email.send();
        }

    2.发送包含附件的邮件(附件为本地资源),这里用到了一个EmailAttachment对象,也就是附件的意思

        /**
         * @describe 发送包含附件的邮件(附件为本地资源)
         * @throws EmailException
         */
        public static void sendEmailsWithAttachments() throws EmailException {
            // 创建一个attachment(附件)对象
            EmailAttachment attachment = new EmailAttachment();
            //设置上传附件的地址
            attachment.setPath("C:\Users\Administrator\Pictures\Saved Pictures\conti.png");
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            //这个描述可以随便写
            attachment.setDescription("Picture of conti");
            //这个名称要注意和文件格式一致,这将是接收人下载下来的文件名称
            attachment.setName("conti.png");
    
            //因为要上传附件,所以用MultiPartEmail()方法创建一个email对象,固定步骤都是一样的
            MultiPartEmail email = new MultiPartEmail();
            email.setHostName("smtp.163.com");
            email.setAuthenticator(new DefaultAuthenticator("myemailaddress@163.com", "myshouquanma"));
            email.setSSLOnConnect(true);
            email.addTo("receiveemail@qq.com", "Conti Zhang");
            email.setFrom("myemailaddress@163.com", "Me");
            email.setSubject("图片");
            email.setMsg("这是发送给你的图片");
            //将附件添加到邮件
            email.attach(attachment);
    
            email.send();
        }

    3.发送包含附近的邮件(附件为在线资源),这个与上传本地附件稍有区别,注意一下就行

       /**
         * @describe 发送包含附件的邮件(附件为在线资源)
         * @throws EmailException
         * @throws MalformedURLException
         */
        public static void sendEmailsWithOnlineAttachments() throws EmailException, MalformedURLException {
            EmailAttachment attachment = new EmailAttachment();
            //设置在线资源路径,和上传本地附件的唯一区别
            attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("Apache logo");
            attachment.setName("Apache logo.gif");
    
            MultiPartEmail email = new MultiPartEmail();
            email.setHostName("smtp.163.com");
            email.setAuthenticator(new DefaultAuthenticator("myemailaddress@163.com", "myshouquanma"));
            email.setSSLOnConnect(true);
            email.addTo("receiveemail@qq.com", "Conti Zhang");
            email.setFrom("myemailaddress@163.com", "Me");
            email.setSubject("The logo");
            email.setMsg("Here is Apache's logo");
            email.attach(attachment);
            email.send();
        }

    4.发送内容为HTML格式的邮件,有些邮件直接打开就是一个HTML页面。虽然不一定用到,可以了解一下

       /**
         * @describe 发送内容为HTML格式的邮件
         * @throws EmailException
         * @throws MalformedURLException
         */
        public static void sendHTMLFormattedEmail() throws EmailException, MalformedURLException {
            // 这里需要使用HtmlEmail创建一个email对象
            HtmlEmail email = new HtmlEmail();
            email.setHostName("smtp.163.com");
            email.setAuthenticator(new DefaultAuthenticator("myemailaddresss@163.com", "myshouquanma"));
            email.addTo("receiveemail@qq.com", "Conti Zhang");
            email.setFrom("myemailaddress@163.com", "Me");
            email.setSubject("Test email with inline image");
    
            // 嵌入图像并获取内容id,虽然案例这样写,但我感觉直接在html内容里面写图片网络地址也可以
            URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
            String cid = email.embed(url, "Apache logo");
    
            // 设置html内容
            email.setHtmlMsg("<html>The apache logo - <img src="cid:" + cid + ""></html>");
    
            // 设置替代内容,如果不支持html
            email.setTextMsg("你的邮件客户端不支持html邮件");
            email.send();
        }

    5.发送内容为HTML格式的邮件(嵌入图片更方便)

    这里用到了DataSourceFileResolver对象,和DataSourceUrlResolver对象,前者可以解析本地文件路径,后者可以解析网络路径

    具体用法如下

        /**
         * @describe 发送内容为HTML格式的邮件(嵌入图片更方便)
         * @throws MalformedURLException
         * @throws EmailException
         */
        public static void sendHTMLFormattedEmailWithEmbeddedImages() throws MalformedURLException, EmailException {
            //html邮件模板
    String htmlEmailTemplate = "<img src="http://www.conti.com/images/1.jpg">"; DataSourceResolver[] dataSourceResolvers =new DataSourceResolver[]{new DataSourceFileResolver(),new DataSourceUrlResolver(new URL("http://"))}; email.setDataSourceResolver(new DataSourceCompositeResolver(dataSourceResolvers)); email.setHostName("smtp.qq.com"); email.setAuthenticator(new DefaultAuthenticator("myemailaddress@qq.com", "myshouquanma")); email.addTo("receiveemail@qq.com", "Conti Zhang"); email.setFrom("myemailaddress@qq.com", "Me"); email.setSubject("Test email with inline image"); email.setHtmlMsg(htmlEmailTemplate); email.setTextMsg("你的邮件客户端不支持html邮件"); email.send(); }

    此种方式可能会报错,会被邮箱认为是有害邮件不接收而导致发送失败。解决方法就是,网易邮箱不行就换QQ邮箱,我就是这样做的

    好了,就这么多,欢迎讨论!

  • 相关阅读:
    9.11 eventbus
    9.10,,,实现new instanceof apply call 高阶函数,偏函数,柯里化
    9.9 promise实现 写完了传到gitee上面了,这里这个不完整
    9.5cors配置代码
    9.5 jsonp 实现
    9.5 http tcp https总结
    9.3 es6 class一部分 and es5 class 发布订阅
    8.30 cookie session token jwt
    8.30vue响应式原理
    warning: LF will be replaced by CRLF in renard-wx/project.config.json. The file will have its original line endings in your working directory
  • 原文地址:https://www.cnblogs.com/conti/p/13145164.html
Copyright © 2011-2022 走看看