一篇文章带你了解Java发送邮件:使用JavaMail API发送电子邮件的注意事项、发送附件等

Java发送邮件:使用JavaMail API发送电子邮件

作者:Stevedash

发表于:2023年8月13日 15点48分

来源:Java 发送邮件 | 菜鸟教程 (runoob.com)

电子邮件在现代通信中扮演着至关重要的角色,而在Java编程中,我们可以利用JavaMail API来方便地实现发送电子邮件的功能。本篇博客将向您介绍如何使用JavaMail API来发送电子邮件,以及一些关键概念和实用示例。


JavaMail API基本概念:

​ JavaMail API是Java平台上用于发送和接收电子邮件的强大库。它提供了一组类和方法,可以用于创建、发送和处理电子邮件。使用JavaMail API,您可以轻松地在Java应用程序中集成电子邮件功能,从而实现诸如发送提醒、通知和报告等任务。


Java 发送邮件

​ 使用Java应用程序发送 E-mail 十分简单,但是首先你应该在你的机器上安装 JavaMail API 和Java Activation Framework (JAF) 。

你也可以使用菜鸟教程提供的下载链接:

下载这俩个Jar文件。您需要把 mail.jaractivation.jar 文件添加到您的 项目中的lib中,然后添加进项目Project Structure➡Libraies➡“+”选择上面俩个架包

在这里插入图片描述

类型服务器名称服务器地址(163为例)SSL协议端口非SSL协议端口号TSL协议端口
收件服务器POPpop.163.com995110
收件服务器IMAPimap.163.com993143
发件服务器SMTPsmtp.163.com465/99425587

腾讯企业邮箱服务器地址:smtp.exmail.qq.com

腾讯邮箱服务器地址:smtp.qq.com

常见问题以及解决办法如下:

1、如果出现454 Command not permitted when TLS active 错误,请检查你的邮件端口配置的是不是25端口,如果是,请改成465端口,并且需要设置 mail.smtp.starttls.enable=false,即可解决问题。

2、部分邮件提供商smtp登录密码不是账号密码,而是授权码,务必注意。使用SSL、TLS这个一定要注意。

3、550 用户被锁定:普通 163 邮箱是无法通过 smtp.163.com 发送邮件的,只有 163 VIP 邮箱才行,然后设置 mail.smtp.host=smtp.vip.163.com

4、550 **Invalid User:**from 必须写成带 @ 的邮件格式,且 username 要用 @ 前面的

5、553 authentication is required:需要设置 mail.smtp.auth=true

步骤概述

以下是使用JavaMail API发送电子邮件的基本步骤:

  1. 设置邮件服务器属性:指定SMTP服务器的主机名、端口、身份验证等属性。
  2. 创建会话对象:使用邮件服务器属性创建一个会话对象,同时提供身份验证信息。
  3. 创建邮件消息:创建一个邮件消息对象,设置发件人、收件人、主题、内容等信息。
  4. 发送邮件:使用会话对象的Transport类发送邮件消息。

需要用户名密码验证邮件发送实例:

本实例以 QQ 邮件服务器为例,你需要在登录QQ邮箱后台在"设置"=》账号中开启POP3/SMTP服务 ,如下图所示:

img

QQ 邮箱通过生成授权码来设置密码:

img

示例代码

①下面是一个简单的Java程序,演示了如何使用JavaMail API发送一封电子邮件:
// 导入必要的类
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class EmailSender {

    public static void main(String[] args) {

        // 设置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.qq.com"); // 设置邮件服务器主机名
        properties.put("mail.smtp.port", "587"); // 设置邮件服务器端口号
        properties.put("mail.smtp.auth", "true"); // 启用身份验证
        properties.put("mail.smtp.starttls.enable", "true"); // 启用 TLS
      //properties.put("mail.smtp.socketFactory.port", "465"); // 设置 SSL 端口
      //properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // 设置 SSL Socket Factory
      //properties.put("mail.smtp.socketFactory.fallback", "false"); // 禁用 SSL 回退

        // 创建会话对象
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("your_email@example.com", "your_password");
                // 在这里填写发送邮件的邮箱地址和密码/授权码
            }
        });

        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("your_email@example.com")); // 设置发件人邮箱
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com")); // 设置收件人邮箱
            message.setSubject("JavaMail API测试"); // 设置邮件主题
            message.setText("这是一封来自JavaMail API的测试邮件。"); // 设置邮件内容

            // 发送邮件
            Transport.send(message);

            System.out.println("邮件发送成功!"); // 打印成功信息

        } catch (MessagingException e) {
            e.printStackTrace(); // 打印异常堆栈信息
        }
    }
}

下面是对于参数的描述:

  • type:要被设置为 TO, CC 或者 BCC,这里 CC 代表抄送、BCC 代表秘密抄送。举例:
  • addresses: 这是 email ID 的数组。在指定电子邮件 ID 时,你将需要使用 InternetAddress() 方法。

Message.RecipientType 枚举类型中,以下几个常量表示不同的收件人类型:

  • TO: 主要收件人,这些人将直接收到邮件的副本。
  • CC: 抄送(Carbon Copy),这些人将收到邮件的副本,但这并不是邮件的主要接收者。
  • BCC: 密送(Blind Carbon Copy),这些人也将收到邮件的副本,但其他收件人无法看到他们的地址。
②在使用 JavaMail API 创建邮件消息时,您可以通过指定这些收件人类型来将不同的收件人添加到邮件消息中。

例如,message.setRecipients(Message.RecipientType.TO, recipientAddresses) 将主要收件人添加到邮件消息中。同样,您可以使用相应的常量来添加抄送和密送收件人。

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class RecipientTypesExample {

    public static void main(String[] args) {

        // 设置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.example.com");
        properties.put("mail.smtp.port", "465");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.socketFactory.port", "465");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");

        // 创建会话对象
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("your_email@example.com", "your_password");
            }
        });

        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("your_email@example.com"));

            // 添加主要收件人(TO)
            Address[] toRecipients = {new InternetAddress("recipient1@example.com")};
            message.setRecipients(Message.RecipientType.TO, toRecipients);

            // 添加抄送(CC)
            Address[] ccRecipients = {new InternetAddress("cc_recipient@example.com")};
            message.setRecipients(Message.RecipientType.CC, ccRecipients);

            // 添加密送(BCC)
            Address[] bccRecipients = {new InternetAddress("bcc_recipient@example.com")};
            message.setRecipients(Message.RecipientType.BCC, bccRecipients);

            message.setSubject("测试邮件收件人类型");
            message.setText("这是一封测试邮件,演示不同的收件人类型。");

            // 发送邮件
            Transport.send(message);

            System.out.println("邮件发送成功!");

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

③发送一封emil给多个收件人,那么使用下面的方法来指定多个收件人ID:
void addRecipients(Message.RecipientType type,Address[] addresses) throws MessagingException

下面的是具体的代码:

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class SecureEmailSender {

    public static void main(String[] args) {

        // 设置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.example.com"); // 设置邮件服务器主机名
        properties.put("mail.smtp.port", "465"); // 设置邮件服务器端口号
        properties.put("mail.smtp.auth", "true"); // 启用身份验证
        properties.put("mail.smtp.socketFactory.port", "465"); // 设置 SSL 端口
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // 设置 SSL Socket Factory
        properties.put("mail.smtp.socketFactory.fallback", "false"); // 禁用 SSL 回退

        // 创建会话对象
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("your_email@example.com", "your_password");
                // 在这里填写发送邮件的邮箱地址和密码
            }
        });

        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("your_email@example.com")); // 设置发件人邮箱

            // 设置多个收件人邮箱
            String[] recipients = {"recipient1@example.com", "recipient2@example.com"};
            Address[] recipientAddresses = new Address[recipients.length];
            for (int i = 0; i < recipients.length; i++) {
                recipientAddresses[i] = new InternetAddress(recipients[i]);
            }
            message.setRecipients(Message.RecipientType.TO, recipientAddresses);

            message.setSubject("JavaMail API测试 - SSL加密"); // 设置邮件主题
            message.setText("这是一封经过SSL加密的测试邮件,发送给多个收件人。"); // 设置邮件内容

            // 发送邮件
            Transport.send(message);

            System.out.println("邮件发送成功!");

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

④发送一封HTML E-mail如下:
package main.mail邮件Api;

// 文件名 SendHTMLEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendHTMLEmail
{
    public static void main(String [] args)
    {

        // 收件人电子邮箱
        String to = "Stevedash@qq.com";

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

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

        // 获取系统属性
        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("Stevedash@qq.com", "dsadasdasdasda"); //发件人邮件用户名、授权码
            }
        });



        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("This is the Subject Line!");

            // 发送 HTML 消息, 可以插入html标签,就是展示出来是页面中的同一个效果
            message.setContent("<h1>This is actual message</h1>",
                    "text/html" );

            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....带网页标签效果的");
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

如下图:

在这里插入图片描述

⑤发送带附件的邮件:
package main.mail邮件Api;

// 文件名 SendFileEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendFileEmail
{
    public static void main(String [] args)
    {

        // 收件人电子邮箱
        String to = "1207036895@qq.com";

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

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

        // 获取系统属性
        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("1207036895@qq.com", "zzzzzzzzzzzzzzzzzzz"); //发件人邮件用户名、授权码
            }
        });

        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("This is the Subject Line!");

            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            // 消息
            messageBodyPart.setText("This is message body");

            // 创建多重消息
            Multipart multipart = new MimeMultipart();

            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart);

            // 附件部分
            messageBodyPart = new MimeBodyPart();
            String filename = "D:/桌面/新建文本文档.txt";
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);

            // 发送完整消息
            message.setContent(multipart );

            //   发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....");
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

可以发现有文件名出现乱码,

下面修改后的代码,解决了编码的问题

package main.mail邮件Api;

import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendFileEmail1 {
    public static void main(String[] args) {
        String to = "1207036895@qq.com";
        String from = "1207036895@qq.com";
        String host = "smtp.qq.com";

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("1207036895@qq.com", "zzzzzzzzzzzzzzzzzzz");
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("这是邮件主题"); // 设置邮件主题,这里使用中文

            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText("这是邮件正文内容"); // 设置邮件正文内容,这里使用中文

            MimeBodyPart attachmentPart = new MimeBodyPart();
            String filename = "D:/桌面/新建文本文档.txt";
            DataSource source = new FileDataSource(filename);
            attachmentPart.setDataHandler(new DataHandler(source));
            attachmentPart.setFileName(MimeUtility.encodeText(source.getName())); // 设置附件文件名,对文件名进行编码

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);
            multipart.addBodyPart(attachmentPart);

            message.setContent(multipart);

            Transport.send(message);
            System.out.println("邮件发送成功!");
        } catch (MessagingException | UnsupportedEncodingException mex) {
            mex.printStackTrace();
        }
    }
}

输出结果如下:

在这里插入图片描述

注意事项和进阶功能

  • 要保护邮箱安全,建议将密码和敏感信息存储在安全的方式中,如配置文件或环境变量。
  • JavaMail API还支持更多高级功能,如附件、HTML内容、抄送、密送等。您可以根据需要进行扩展。
  • 为了避免被邮件服务器标记为垃圾邮件,确保邮件内容和行为遵循电子邮件的最佳实践。

总结

​ JavaMail API为Java程序员提供了发送电子邮件的便捷途径。通过设置邮件服务器属性、创建会话对象以及构建邮件消息,我们可以轻松地在Java应用程序中实现电子邮件发送功能。在实际项目中您可以根据不同场景的不同需求,采用如附件、HTML内容和抄送等应对。

作者:Stevedash

发表于:2023年8月13日 15点48分

来源:Java 发送邮件 | 菜鸟教程 (runoob.com)

注:本文内容基于个人学习理解,如有错误或疏漏,欢迎指正。感谢阅读!如果觉得有帮助,请点赞和分享。

  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Stevedash

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值