写一个javamail工具类,并写好注释,再写好一个测试模板
时间: 2023-04-09 19:01:15 浏览: 50
好的,我可以回答这个问题。以下是一个简单的 JavaMail 工具类,它可以用来发送电子邮件。请注意,这只是一个示例,您需要根据自己的需求进行修改。
```
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class JavaMailUtil {
public static void sendEmail(String recipient, String subject, String body) 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.gmail.com");
properties.put("mail.smtp.port", "587");
// 创建会话
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email@gmail.com", "your-password");
}
});
// 创建邮件
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email@gmail.com"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
message.setSubject(subject);
message.setText(body);
// 发送邮件
Transport.send(message);
}
}
```
以下是一个测试模板,您可以使用它来测试您的 JavaMail 工具类:
```
public class JavaMailTest {
public static void main(String[] args) {
try {
JavaMailUtil.sendEmail("recipient@example.com", "Test Subject", "This is a test email.");
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
System.out.println("Failed to send email. Error message: " + e.getMessage());
}
}
}
```
请注意,您需要将“your-email@gmail.com”和“your-password”替换为您自己的电子邮件地址和密码。