java后台发送邮件
以下是Java后台发送邮件的示例代码。请注意,您需要使用JavaMail API和Java Activation Framework(JAF)库才能运行此代码。
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMail {
public static void main(String[] args) {
// 收件人的电子邮件ID
String to = "recipient@example.com";
// 发件人的电子邮件ID
String from = "sender@example.com";
// 指定主机名
String host = "smtp.gmail.com";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.auth", "true");
// 获取默认的Session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
try {
// 创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session);
// 设置From: 头部头字段
message.setFrom(new InternetAddress(from));
// 设置To: 头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 设置主题
message.setSubject("This is the Subject Line!");
// 设置实际消息
message.setText("This is actual message");
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
请注意,此代码仅适用于发送简单的文本消息。如果您需要发送带有附件或HTML格式的消息,则需要使用其他方法
原文地址: https://www.cveoy.top/t/topic/fdfO 著作权归作者所有。请勿转载和采集!