写一个javamail工具类,并写好注释
时间: 2023-04-09 15:01:15 浏览: 70
好的,我可以回答这个问题。以下是一个简单的JavaMail工具类的示例代码,包括注释:
```java
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.host", "smtp.gmail.com"); // 邮件服务器地址
properties.put("mail.smtp.port", "587"); // 邮件服务器端口
properties.put("mail.smtp.auth", "true"); // 需要认证
// 创建Session对象
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 API发送邮件。在使用之前,你需要替换掉代码中的发件人邮箱和密码,以及邮件服务器地址和端口。使用时,只需要调用`sendEmail`方法,传入收件人邮箱、邮件主题和邮件内容即可发送邮件。