用JavaMail发送txt
时间: 2024-03-12 12:47:44 浏览: 26
可以使用JavaMail API来发送纯文本邮件,下面是一个简单的例子:
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendTextEmail {
public static void main(String[] args) {
final String username = "你的邮箱地址";
final String password = "你的邮箱密码";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, 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("邮件主题");
message.setText("邮件内容");
Transport.send(message);
System.out.println("邮件发送成功!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
其中,需要替换的部分包括:
- `username`:你的邮箱地址
- `password`:你的邮箱密码
- `message.setFrom(new InternetAddress("发件人邮箱地址"))`:发件人的邮箱地址
- `message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("收件人邮箱地址"))`:收件人的邮箱地址
- `message.setSubject("邮件主题")`:邮件的主题
- `message.setText("邮件内容")`:邮件的内容
你需要确保你的邮箱已经开启了SMTP服务。如果你使用的是Gmail邮箱,你可能需要在你的邮箱账户中允许不太安全的应用程序访问你的邮箱。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)