java发邮件如何获取到结果

   2025-02-15 7510
核心提示:在Java中发送邮件时,可以使用JavaMail API来发送邮件。发送邮件后,可以通过检查发送结果来获取结果。以下是一个示例代码,演示

在Java中发送邮件时,可以使用JavaMail API来发送邮件。发送邮件后,可以通过检查发送结果来获取结果。以下是一个示例代码,演示如何发送邮件并获取发送结果:

import javax.mail.*;import javax.mail.internet.*;import java.util.Properties;public class SendEmail {    public static void main(String[] args) {        // 配置邮件服务器        Properties properties = new Properties();        properties.put("mail.smtp.host", "smtp.example.com");        properties.put("mail.smtp.port", "587");        properties.put("mail.smtp.auth", "true");                // 创建Session对象        Session session = Session.getInstance(properties, new Authenticator() {            @Override            protected PasswordAuthentication getPasswordAuthentication() {                return new PasswordAuthentication("your-email@example.com", "your-password");            }        });                try {            // 创建Message对象            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("Hello, World!");            message.setText("This is a test email.");                        // 发送邮件            Transport.send(message);                        // 邮件发送成功            System.out.println("Email sent successfully!");        } catch (MessagingException e) {            // 邮件发送失败            System.out.println("Email sending failed: " + e.getMessage());        }    }}

在上面的代码中,使用JavaMail API配置了邮件服务器,并创建了一个Session对象。通过在Session对象中传递用户名和密码,实现了身份验证。然后,创建了一个Message对象,设置了发件人、收件人、主题和正文。最后,调用Transport.send()方法发送邮件。

如果邮件发送成功,将打印"Email sent successfully!“。如果邮件发送失败,将打印"Email sending failed”,并附上错误信息。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言