JAVA 发送邮件

// 文件路径 D:ApacheServerweb_javaHelloWorldsrccom	estTestSendMail.java
package com.test;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class TestSendMail {

    public void testfun(){

        // 需要先下载 javax.mail.jar 和 activation.jar。只发文字邮件 javax.mail.jar 就够了,发附件则还需要 activation.jar
        // mail.jar 下载地址 https://www.oracle.com/technetwork/java/javamail/index.html 点击 Downloads 下载 JavaMail API 1.4.7,或者 https://javaee.github.io/javamail/ 下载 JavaMail 1.6.2 这里版本是 JavaMail 1.6.2 
        // jaf 下载页面 https://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-plat-419418.html 这里用到版本 JavaBeans Activation Framework 1.1.1
        // 提取下载的压缩包里的 javax.mail.jar 和 activation.jar 放到项目中
        
        
        // 收件人的电子邮件 ID
        String to = "32705317@qq.com";
        // 发件人的电子邮件 ID
        String from = "zdy_521@126.com";
        // SMTP服务器地址
        String host = "smtp.126.com";
        // 授权密码,到网易邮箱中设置
        String passWord = "87477zhang";
        // 设置邮件发送相关属性
        Properties properties = System.getProperties();
        
        // 设置邮件传输采用的协议smtp(这里使用网易的smtp服务器)
        properties.setProperty("mail.transport.protocol", "smtp");
        //设置发送邮件的邮件服务器的属性
        properties.setProperty("mail.smtp.host", host);
        //需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
        properties.setProperty("mail.smtp.auth", "true");
        
        // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
        // 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
        // QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
        /*
        final String smtpPort = "465";
        properties.setProperty("mail.smtp.port", smtpPort);
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        properties.setProperty("mail.smtp.socketFactory.port", smtpPort);
        */
        
        // 获取默认的 Session 对象
        Session session = Session.getDefaultInstance(properties);
        // 会话采用debug模式
        session.setDebug(true);
        try {
            // 创建邮件对象
            MimeMessage message = new MimeMessage(session);
            // 设置发送邮件地址,param1 代表发送地址 param2 代表发送的名称(任意的) param3 代表名称编码方式
            message.setFrom(new InternetAddress(from, "发件人名称", "utf-8"));
            // 代表收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to, "收件人名称", "utf-8"));
            // To: 增加更多收件人(可选)
            //message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("chimuhuadao@126.com", "收件人名称", "UTF-8"));
            //message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("chimuhuadao@163.com", "收件人名称", "UTF-8"));
            // Cc: 抄送(可选)
            //message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("chimuhuadao@126.com", "抄送人名称", "UTF-8"));
            // Bcc: 密送(可选)
            //message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("chimuhuadao@126.com", "密送人名称", "UTF-8"));
            // 设置邮件主题
            message.setSubject("测试转发邮件");
            
            
            
            //====================附件测试开始=================
            //以下部分为测试邮件附件,如不需要可以把整段附件这部分代码注释
            
            // 创建 Multipart 对象,来包含邮件的多部分(正文,附件等)消息
            Multipart multipart = new MimeMultipart();
            
            // 第一部分正文消息部分 
            BodyPart bodyPart = new MimeBodyPart();
            // 设置邮件正文内容
            bodyPart.setContent("<h1>早安,世界</h1>", "text/html;charset=utf-8");
            // 将正文消息部分添加到 Multipart 对象中
            multipart.addBodyPart(bodyPart);
    
    
            // 第二部分是附件
            bodyPart = new MimeBodyPart();
            // 读取项目根目录下 upload 文件夹内 00125943U-0.jpg 文件作为附件,这里路径为 D:/ApacheServer/web_java/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/HelloWorld/upload/00125943U-0.jpg。这里WebContent为实际项目运行根目录
            String fileName = "00125943U-0.jpg";
            // 获取项目运行根目录
            // .toString().substring(6) 消除返回路径中的 file:/ 字符串,这里返回路径为 D:/ApacheServer/web_java/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/HelloWorld/
            String appBase = Thread.currentThread().getContextClassLoader().getResource("../../").toString().substring(6);
            // 合成文件绝对路径
            String filePath = appBase + "upload" + File.separator + fileName;
            DataSource dataSource = new FileDataSource(filePath);
            bodyPart.setDataHandler(new DataHandler(dataSource));
            // 设置邮件中附件名称
            bodyPart.setFileName("testAttachment.jpg");
            // 将附件部分添加到 Multipart 对象中
            multipart.addBodyPart(bodyPart);
            //response.getWriter().append(filePath);if(true)return;
            
            // 另一份附件,可发送多个附件
            bodyPart = new MimeBodyPart();
            // 读取项目根目录下 upload 文件夹内 00125943U-0.jpg 文件作为附件
            fileName = "abc.ppt";
            filePath = appBase + "upload" + File.separator+ fileName;
            dataSource = new FileDataSource(filePath);
            bodyPart.setDataHandler(new DataHandler(dataSource));
            // 设置邮件中附件名称
            bodyPart.setFileName("testAttachment.ppt");
            // 将附件部分添加到 Multipart 对象中
            multipart.addBodyPart(bodyPart);
            
            
            //和下面发送文本的 message.setContent("<h1>早安,世界</h1>", "text/html;charset=utf-8"); 二选一执行
            message.setContent(multipart);
            //====================附件测试结束=================
            
            
            // 设置邮件内容,可以带HTML标签,也可以不带,内容大小不限
            //message.setContent("<h1>早安,世界</h1>", "text/html;charset=utf-8");
            // 设置发送时间
            message.setSentDate(new Date());
            // 保存上面的编辑内容
            message.saveChanges();
            
            Transport transport = session.getTransport();
            // 链接邮件服务器
            transport.connect(from, passWord);
            // 发送信息
            transport.sendMessage(message, message.getAllRecipients());
            // 关闭链接
            transport.close();
        }catch(Exception exception) {
            // 处理错误
            exception.printStackTrace();
        }
    
    }
}
原文地址:https://www.cnblogs.com/dreamhome/p/11486702.html