Java实现发送邮件的代码可以使用JavaMail库来完成。以下是一个简单的示例代码:```javaimport javax.mai
Java实现发送邮件的代码可以使用JavaMail库来完成。以下是一个简单的示例代码:
```java
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服务器地址和接收方邮箱地址。
--结束END--
本文标题: java实现发送邮件代码怎么写
本文链接: https://www.lsjlt.com/news/415876.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-10
2024-05-10
2024-05-10
2024-05-10
2024-05-10
2024-05-10
2024-05-10
2024-05-10
2024-05-10
2024-05-10
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0