使用JavaMail实现发送邮件

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class test{
    public static void sendEmail(String recipient) throws MessagingException {
        // 配置邮件服务器
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.xx.com"); // 使用您的SMTP服务器
        properties.put("mail.smtp.port", "xx"); // SMTP端口

        // 邮件账号信息
        final String myAccountEmail = "xx@xx.com"; // 发件人邮箱
        final String password = "在你开启邮箱POP3/SMTP后生成的授权码"; // 发件人密码

        // 创建会话
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(myAccountEmail, password);
            }
        });

        // 创建邮件内容
        Message message = prepareMessage(session, myAccountEmail, recipient);

        // 发送邮件
        Transport.send(message);
        System.out.println("邮件成功发送!");
    }

    private static Message prepareMessage(Session session, String myAccountEmail, String recipient) {
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(myAccountEmail));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            message.setSubject("您的邮件主题");
            message.setText("你好");
            return message;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws MessagingException {
        sendEmail("xx@xx.com"); // 收件人邮箱
    }

}

//``此代码中,您需要替换SMTP服务器地址、端口、发件人邮箱、密码以及收件人邮箱等信息。

注意事项

在使用JavaMail发送邮件时,确保您使用的邮箱服务允许通过SMTP发送邮件,并且您已正确配置了所有必要的设置(如服务器地址、端口、用户名、密码等)。
为了安全起见,不要在代码中硬编码您的邮箱密码。考虑使用环境变量或其他安全方式存储密码。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值