java用qq邮箱发邮件
时间: 2023-10-23 20:14:14 浏览: 125
Java QQ邮箱发送邮件
要使用 Java 发送邮件,需要使用 Java Mail API。以下是一个使用 QQ 邮箱发送邮件的示例代码:
```java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SendMail {
public static void main(String[] args) {
final String username = "your_qq_email@qq.com";
final String password = "your_qq_password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.qq.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("your_qq_email@qq.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient_email@example.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
在代码中,需要将 `your_qq_email@qq.com` 和 `your_qq_password` 替换为你的 QQ 邮箱地址和授权码。授权码需要在 QQ 邮箱的设置中生成,具体操作可以参考 QQ 邮箱的帮助文档。另外,需要将 `recipient_email@example.com` 替换为收件人的邮箱地址。
阅读全文