我想编写一个可以向任何 Gmail 帐户发送电子邮件的 Java 程序。 我正在为此目的搜索 API。到目前为止,我发现 Gmail API 很有用。我还在 Google 的开发者控制台上创建了一个 APP。我在 Gmail API 中找不到任何 Oauth 授权和电子邮件发送的示例。任何人都可以引用任何 Material 或链接吗?
最佳答案
试试 JavaMail API 要使用它,您需要两个依赖项:javaee.jar 和 mail.jar
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@no-spam.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to@no-spam.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
关于java - 在 java 中使用 Gmail API 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33258415/