使用JavaMail发送电子邮件可以通过以下步骤实现:
以下是一个示例代码,演示如何使用JavaMail发送电子邮件:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class EmailSender {
public static void main(String[] args) {
// 配置SMTP服务器信息
String host = "smtp.example.com";
int port = 587;
String username = "your_username";
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", host);
props.put("mail.smtp.port", port);
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("sender@example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
message.setSubject("Hello, World!");
message.setText("This is a test email.");
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
在上述示例代码中,需要将host
、port
、username
和password
替换为实际的SMTP服务器信息。同时,需要将sender@example.com
和recipient@example.com
替换为实际的发件人和收件人邮箱地址。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)
领取专属 10元无门槛券
手把手带您无忧上云