java怎么实现发送邮件功能

55次阅读
没有评论

共计 1453 个字符,预计需要花费 4 分钟才能阅读完成。

要在 Java 中实现发送邮件的功能,可以使用 Java Mail API。以下是一个简单的示例代码:

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

public class SendEmail {public static void main(String[] args) {// 邮件发送者和接收者的邮箱地址
        String from = "sender@example.com";
        String to = "recipient@example.com";

        // 设置 SMTP 服务器地址和端口号
        String host = "smtp.example.com";
        int port = 465;

        // 邮件发送者的用户名和密码
        String username = "sender@example.com";
        String password = "password";

        // 创建 Properties 对象,并设置邮件服务器相关配置
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");

        // 创建 Session 对象
        Session session = Session.getInstance(props, new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username, password);
            }
        });

        try {// 创建 Message 对象,并设置邮件发送者、接收者、主题和正文
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject("Hello");
            message.setText("This is a test email.");

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

            System.out.println("Email sent successfully.");
        } catch (MessagingException e) {e.printStackTrace();
        }
    }
}

在代码中,需要将 fromto变量设置为实际的邮箱地址,host变量设置为 SMTP 服务器地址,port变量设置为 SMTP 服务器端口号,usernamepassword 变量设置为发送邮件的邮箱的用户名和密码。

该代码使用 Java Mail API 创建了一个邮件会话(Session)对象,并设置了 SMTP 服务器的相关配置。然后,创建了一个 Message 对象,设置了邮件的发送者、接收者、主题和正文。最后,调用 Transport.send() 方法发送邮件。

注意:为了使用 Java Mail API,你需要将相关的 Jar 文件添加到你的 Java 项目的类路径中。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计1453字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)