java 使用google发送邮件
要使用Java代码发送电子邮件,需要使用JavaMail API和Java Activation Framework(JAF)。以下是使用Google SMTP服务器发送电子邮件的示例代码:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) {
// 收件人电子邮件ID
String to = "recipient@gmail.com";
// 发件人电子邮件ID
String from = "sender@gmail.com";
// Google SMTP服务器
String host = "smtp.gmail.com";
// 获取系统属性
Properties properties = System.getProperties();
// 设置SMTP服务器
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.auth", "true");
// 获取默认的Session对象
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("sender@gmail.com", "password");
}
});
try {
// 创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(from));
// 设置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 设置主题
message.setSubject("Test Email");
// 设置消息正文
message.setText("This is a test email.");
// 发送消息
Transport.send(message);
System.out.println("Message sent successfully.");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
在上面的代码中,我们使用Google SMTP服务器(smtp.gmail.com)发送电子邮件。要使用此代码,您需要将收件人和发件人的电子邮件ID替换为实际值,并将发件人的密码替换为实际密码。此外,您需要在类路径中包含JavaMail API和JAF
原文地址: https://www.cveoy.top/t/topic/cSjl 著作权归作者所有。请勿转载和采集!