import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class test{
public static void sendEmail(String recipient) throws MessagingException {
// 配置邮件服务器
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.xx.com"); // 使用您的SMTP服务器
properties.put("mail.smtp.port", "xx"); // SMTP端口
// 邮件账号信息
final String myAccountEmail = "xx@xx.com"; // 发件人邮箱
final String password = "在你开启邮箱POP3/SMTP后生成的授权码"; // 发件人密码
// 创建会话
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(myAccountEmail, password);
}
});
// 创建邮件内容
Message message = prepareMessage(session, myAccountEmail, recipient);
// 发送邮件
Transport.send(message);
System.out.println("邮件成功发送!");
}
private static Message prepareMessage(Session session, String myAccountEmail, String recipient) {
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(myAccountEmail));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
message.setSubject("您的邮件主题");
message.setText("你好");
return message;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) throws MessagingException {
sendEmail("xx@xx.com"); // 收件人邮箱
}
}
//``此代码中,您需要替换SMTP服务器地址、端口、发件人邮箱、密码以及收件人邮箱等信息。
注意事项
在使用JavaMail发送邮件时,确保您使用的邮箱服务允许通过SMTP发送邮件,并且您已正确配置了所有必要的设置(如服务器地址、端口、用户名、密码等)。
为了安全起见,不要在代码中硬编码您的邮箱密码。考虑使用环境变量或其他安全方式存储密码。