java实现发送邮件代码怎么写

38次阅读
没有评论

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

Java 实现发送邮件的代码可以使用 JavaMail 库来完成。以下是一个简单的示例代码:

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmail {public static void main(String[] args) {
// 发送方邮箱地址
String fromEmail = "your_email@example.com";
// 发送方邮箱密码或授权码
String password = "your_password";
// 接收方邮箱地址
String toEmail = "recipient_email@example.com";
// 配置 SMTP服务器  的属性
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// 创建 Session 对象
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(fromEmail, password);
}
});
try {
// 创建 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(fromEmail));
// 设置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
// 设置邮件主题
message.setSubject("Test Email");
// 设置邮件内容
message.setText("This is a test email.");
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully!");
} catch (MessagingException e) {e.printStackTrace();
}
}
}

请注意,你需要将代码中的 ”your_email@example.com”,”your_password”,”smtp.example.com”,”recipient_email@example.com” 替换为你自己的邮箱地址、密码、SMTP 服务器地址和接收方邮箱地址。

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

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