javax.mail 不需要授权需要账号密码发送邮件的代码怎么写
时间: 2023-06-05 16:08:04 浏览: 238
以下是使用账号密码发送邮件的 Java 代码示例:
```
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendMail {
public static void main(String[] args) {
final String username = "你的邮箱账号";
final String password = "你的邮箱密码";
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.xxx.com");// 设置邮件服务器
prop.put("mail.smtp.auth", "true");// 进行授权认证
prop.put("mail.smtp.port", "25");// 设置邮件发送端口
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);// 登录账号和密码
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("发件人邮箱地址"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("收件人邮箱地址")
);
message.setSubject("邮件主题");
// 邮件内容可以是纯文本,也可以是 HTML 格式
message.setText("邮件内容");
Transport.send(message);
System.out.println("邮件已发送");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,需要填写的信息有:
- 你的邮箱账号和密码:分别在 `username` 和 `password` 中填写。
- 邮件服务器:在 `mail.smtp.host` 中填写你所使用的邮件服务器的主机名(例如,使用网易 163 邮箱发送邮件,主机名为 `smtp.163.com`)。
- 发送邮件的地址、收件人地址和邮件主题:在 `message.setFrom`、`InternetAddress.parse` 和 `message.setSubject` 中填写。
- 邮件内容:在 `message.setText` 中填写邮件内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)