怎样用java发送邮件
发布网友
发布时间:2022-04-19 23:27
我来回答
共1个回答
热心网友
时间:2023-07-17 23:37
首先下载 JavaMail jar 包,并导入到项目中。下载地址
编写代码,代码如下:
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class App45 {
public static void main(String[] args) throws AddressException, MessagingException {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "邮件发送服务器");
properties.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 设置发件人邮件帐号和密码
return new PasswordAuthentication("邮件帐号", "密码");
}
});
MimeMessage message = new MimeMessage(session);
// 设置发件人邮件地址
message.setFrom(new InternetAddress("发件人邮件地址"));
// 设置收件人邮件地址
message.addRecipient(Message.RecipientType.TO, new InternetAddress("收件人邮件地址"));
message.setSubject("这里是邮件主题。");
message.setText("这里是邮件内容。");
Transport.send(message);
}
}