Java实现发送邮件(发送方为QQ邮箱)
时间: 2023-12-20 11:07:33 浏览: 42
Java实现发送邮件的方法有很多种,其中一种方法是使用SMTP协议发送邮件。你可以通过读取配置文件来获取发送方的邮箱账号和密码。下面是一个简单的Java代码示例,供你参考:
```java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
public static void main(String[] args) {
final String username = "your_email@qq.com";
final String password = "your_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 Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient_email@example.com"));
message.setSubject("Subject");
message.setText("Hello, World!");
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
```
请注意将代码示例中的`your_email@qq.com`替换为你的QQ邮箱账号,`your_password`替换为你的QQ邮箱密码,以及`recipient_email@example.com`替换为你要发送邮件的收件人邮箱。