我是 APP Engine Google 世界的新手,但我在那里有我的项目,为了发送电子邮件,我正在使用 JavaMail API,它运行良好,但我需要将“发件人”字段更改为不存在的帐户或与我的个人帐户不同(我不确定是否有必要在 APP Engine 中注册我需要在“发件人”字段中显示的帐户)。我发送的电子邮件使用我在“发件人”字段中经过身份验证的帐户(这很明显,不是吗)。那么问题是这是否可能?我也从这个网站上阅读了很多关于这个问题的网站,但我仍然没有工作。 Google APP引擎在API管理器中有Gmail API,但我不确定它是否与使用JavaMail API相同。
我的一些代码发送电子邮件但使用我的帐户的身份验证:
public void sendEmail(String[] recipients, String subject, String body, String username, String password) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true"); //I tried disabling this but it not works
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
props.put("mail.smtp.port", "587"); //I tried with another port
//I tried without authentication from my account like this:
//Session.getDefaultInstance(props, null);
//It not works
session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MailService.this.username, MailService.this.password);
}
});
Message message = new MimeMessage(session);
// Here is the key, sending email not from authenticated account
message.setFrom(new InternetAddress("whateveraccount@example.com", "whateveraccount.engine@example.com"));
message.setReplyTo(InternetAddress.parse("whateveraccount@example.com",false));
//Sending to multiple recipients
Address[] to = new Address[recipients.length];
for (int i=0; i<recipients.length; i++) {
to[i] = new InternetAddress(recipients[i]);
}
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
/**
Multi part message email
**/
Multipart multipart = new MimeMultipart();
//body
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(body, "text/html");
multipart.addBodyPart(htmlPart);
// adds attachments
String[] attachFiles = new String[2];
attachFiles[0] = "..path to send attachment..";
attachFiles[1] = "..path to send attachment..";
if(attachFiles != null && attachFiles.length > 0){
for (String filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
message.setContent(multipart);
Transport.send(message);
}
更新: 更具体地说,我需要 Google App Engine 中的配置。
最佳答案
通过使用 Sendgrid,您可以从控制台中声明的域之外的其他域发送电子邮件。
你只需要做类似的事情:
SendGrid sendgrid = new SendGrid(Constants.SENDGRID_API_KEY);
SendGrid.Email email = new SendGrid.Email();
email.addTo("recipient@gmail.com");
email.setFrom("whatever@whatever.com");
email.setFromName("Whatever");
email.setSubject(...);
....
文档非常好,从 AppEngine Mail API 切换到 Sendgrid 非常简单
关于java - 如何通过 Google App Engine 使用 JavaMail 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37884386/