Java 发送邮件

一、java发送Email需要引入email jar包,依赖如下:

        <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

二、代码如下,使用139邮箱发送:

复制代码
// 收件人电子邮箱
//         String to = "*********@163.com";
        String to = "*********@qq.com";

        // 发件人电子邮箱
        String from = "*********@139.com";


        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp.139.com";  //139 邮件服务器

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");

        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(from, "********"); //发件人邮件用户名、密码
            }
        });

        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: 头部头字段
            message.setSubject("邮件头部!");
            // 设置消息体 message.setContent("测试", "text/html;charset=utf-8");
            // 设置内容  如果我们所使用的MimeMessage中信息内容是文本的话,我们便可以直接使用setText()方法来方便的设置文本内容
            message.setContent("<h2 style=\"color: red\">Hello World!</h2>\n", "text/html;charset=utf-8");
            // 发送消息
            Transport.send(message);
            System.out.println("发送 信息 成功....");
        }catch (MessagingException e) {
            e.printStackTrace();
        }
复制代码

三、如果是QQ邮件的话,需要引入另一个包 进行加密  不加密也可以发送

加密的话需要引入另一个包

        <!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.1</version>
        </dependency>

 

复制代码
 // 收件人电子邮箱
//         String to = "*******@163.com";
         String to = "*******@qq.com";

        // 发件人电子邮箱
         String from = "*******@qq.com";


        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp.qq.com";  //QQ 邮件服务器

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");

        // 下面四行不加也可以发送
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                 return new PasswordAuthentication(from , "*******"); //发件人邮件用户名、密码
            }
        });

        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: 头部头字段
            message.setSubject("邮件标题");
            // 设置消息体 message.setContent("测试", "text/html;charset=utf-8");
            // 设置内容  如果我们所使用的MimeMessage中信息内容是文本的话,我们便可以直接使用setText()方法来方便的设置文本内容
            message.setText("This is actual message");
            // 发送消息
            Transport.send(message);
            System.out.println("发送成功....");
        }catch (MessagingException e) {
            e.printStackTrace();
        }
复制代码

 四、发送163邮件

复制代码
public static void send163Mail(String toMail,String fromMail,String pwd,String content,String title) throws Exception{
        Properties prop = new Properties();
        prop.setProperty("mail.host", host_163); //// 设置163邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议
        prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码

        // 关于QQ邮箱,还要设置SSL加密,加上以下代码即可
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        //使用JavaMail发送邮件的5个步骤

        //创建定义整个应用程序所需的环境信息的 Session 对象

        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication(fromMail, pwd);
            }
        });

        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(fromMail));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));

            // Set Subject: 头部头字段
            message.setSubject(title);
            // 设置消息体 message.setContent("测试", "text/html;charset=utf-8");
            // 设置内容  如果我们所使用的MimeMessage中信息内容是文本的话,我们便可以直接使用setText()方法来方便的设置文本内容
            message.setContent("<h2 style=\"color: red\">"+content+"</h2>\n", "text/html;charset=utf-8");
            // 发送消息
            Transport.send(message);
            System.out.println("发送 信息 成功....");
        }catch (MessagingException e) {
            e.printStackTrace();
        }
复制代码

 

四、发送邮件并携带附件,邮件内容html格式,代码如下:

复制代码
package com.mmall.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.*;

public class SendMailFile {
    // MIME邮件对象
    private static MimeMessage mimeMsg;

    // 邮件会话对象
    private static Session session;
    // 系统属性
    private static Properties properties= System.getProperties();;
    // Multilpart对象,邮件内容,标题,附件等内容均添加到其中后再生成
    private static Multipart mp;
    // 发件人用户名
    private static String username="251231466@qq.com";
    // 发件人密码
    private static String password="whgodxpzprb";
    // 发件人昵称
    private static String nickname="wanghao";

    // 收件人
    private static String sendName="ssrs_wanghao@163.com";
    // smtp
    private static String smtp="smtp.qq.com";

    public static void main(String[] args) {

        //设置邮件发送的SMTP主机
        properties.put("mail.smtp.host", smtp);
        properties.put("mail.smtp.auth", "true");

        if(smtp!=null && smtp.indexOf("qq")>0){
            // 下面四行不加也可以发送      QQ邮箱设置
            System.out.println("进入setQQ 加密");
            MailSSLSocketFactory sf = null;
            try {
                sf = new MailSSLSocketFactory();
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
            assert sf != null;
            sf.setTrustAllHosts(true);

            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
        }


        // 获取邮件会话对象
       session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(username, password); //发件人邮件用户名、密码
            }
        });


        // 创建邮件MIME对象
        mimeMsg = new MimeMessage(session);
        mp = new MimeMultipart();
        try {
            nickname = MimeUtility.encodeText(nickname, "utf-8", "B");
            mimeMsg.setFrom(new InternetAddress(nickname + "<" + username + ">"));
            // 将收件人数组设置为InternetAddress数组类型
            String [] receivers= new String[] {sendName};
            List<InternetAddress> receiverList = new ArrayList<InternetAddress>();
            for (String receiver : receivers) {
                receiverList.add(new InternetAddress(receiver));
            }
            InternetAddress[] addresses = receiverList.toArray(new InternetAddress[receivers.length]);
            mimeMsg.setRecipients(Message.RecipientType.TO, addresses);

            // 将抄送人数组设置为InternetAddress数组类型
            String [] copyTos = new String[0];
            List<InternetAddress> copyToList = new ArrayList<InternetAddress>();
            for (String copyto : copyTos) {
                copyToList.add(new InternetAddress(copyto));
            }
            InternetAddress[] copyAddresses = copyToList.toArray(new InternetAddress[copyTos.length]);
            mimeMsg.setRecipients(Message.RecipientType.CC, copyAddresses);

            Map<String,String> map = new HashMap<>();
            map.put("file1","C:/Users/Administrator/Desktop/teset.txt");
            map.put("file2","C:/Users/Administrator/Desktop/teset - 副本.txt");
            setFileAffix(map);

            mimeMsg.setSubject(MimeUtility.encodeText("主题:测试发送邮件带文件", "utf-8", "B"));
            // 内容
            BodyPart bp = new MimeBodyPart();
            bp.setContent("" + "<!DOCTYPE html>\n" +
                    "<html lang=\"en\">\n" +
                    "<head>\n" +
                    "    <meta charset=\"UTF-8\">\n" +
                    "    <title>Title</title>\n" +
                    "    <script type=\"text/javascript\">\n" +
                    "        function f() {\n" +
                    "            alert('你点击了');\n" +
                    "        }\n" +
                    "    </script>\n" +
                    "</head>\n" +
                    "<body>\n" +
                    "    <h1 style=\"color: red\" onclick=\"f()\">这是一封测试发送邮件带附件的邮件</h1>\n" +
                    "<p style=\"color: #000bff;\">不用回复,我就看下css样式</p>\n" +
                    "<input type=\"button\" onclick=\"f()\"  value=\"我是一个按钮\"/>\n" +
                    "</body>\n" +
                    "</html>\n", "text/html;charset=utf-8");
            mp.addBodyPart(bp);

            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();

            Transport transport = session.getTransport("smtp");
            transport.connect((String) properties.get("mail.smtp.host"), username, password);
            transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
            transport.close();



        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }/**
     * 添加邮件附件,附件可为多个
     * @param fileMap 文件绝对路径map集合
     * @throws MessagingException
     */
    public static void setFileAffix(Map<String, String> fileMap) throws MessagingException, UnsupportedEncodingException {
        // 获取附件
        for (String file: fileMap.keySet()) {
            // 创建一个存放附件的BodyPart对象
            BodyPart bp = new MimeBodyPart();
            // 获取文件路径
            String filePath = fileMap.get(file);
            String[] fileNames = filePath.split("/");
            // 获取文件名
            String fileName = fileNames[fileNames.length-1];
            // 设置附件名称,附件名称为中文时先用utf-8编码
            bp.setFileName(MimeUtility.encodeWord(fileName, "utf-8", null));
            FileDataSource fields = new FileDataSource(filePath);
            bp.setDataHandler(new DataHandler(fields));
            // multipart中添加bodypart
            mp.addBodyPart(bp);
        }
    }

}
复制代码

 

 其它:

 

 

文章参考:

https://blog.csdn.net/Cindypin/article/details/79026910

邮件api介绍:

https://blog.csdn.net/imain/article/details/1453677

 

posted @   苦心明  阅读(617)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示