从Throlle添加的更新上面的回答。 有上面可能还有一些差异与Gmail API的更新版本
发送消息,并按照其默认提供标准的发送标准的电子邮件:
这是Grails的,但你可以很容易地改变java,控制器的东西在这个html的东西可以是found here。也许当我完成了我在做什么,并有机会将与所有这些例子更新GitHub的网站:
在控制器:
def sendHTMLEmail() {
String emailBox='[email protected]'
String to ='[email protected]'
String html="<html><body><table><tr><td><b>aa</b></td><td>bb</td></tr></table><h1>html content</h1></body></html>"
MimeMessage content = gmailService.createHTMLEmail(to,emailBox,'gmail test','testing gmail via app',html)
def message = gmailService.sendMessage(gmail,'me',content)
render "=== ${message.id}"
}
在服务:
public static MimeMessage createHTMLEmail(String to, String from, String subject, String text, String html) {
Properties props = new Properties()
Session session = Session.getDefaultInstance(props, null)
MimeMessage email = new MimeMessage(session)
Multipart multiPart = new MimeMultipart("alternative")
email.setFrom(new InternetAddress(from))
email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to))
email.setSubject(subject)
MimeBodyPart textPart = new MimeBodyPart()
textPart.setText(text, "utf-8")
MimeBodyPart htmlPart = new MimeBodyPart()
htmlPart.setContent(html, "text/html; charset=utf-8")
multiPart.addBodyPart(textPart)
multiPart.addBodyPart(htmlPart)
email.setContent(multiPart)
return email
}
然后他们标准提供了sendMessage(下面的位可以在github链接上找到):
public static Message sendMessage(Gmail service,String userId,MimeMessage emailContent) throws MessagingException, IOException {
try {
Message message = createMessageWithEmail(emailContent)
message = service.users().messages().send(userId, message).execute()
return message
} catch (Exception e) {
//log.error "${e}"
}
}
and createMessag eWithEmail
public static Message createMessageWithEmail(MimeMessage emailContent) throws MessagingException, IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream()
emailContent.writeTo(buffer)
byte[] bytes = buffer.toByteArray()
String encodedEmail = Base64.encodeBase64URLSafeString(bytes)
Message message = new Message()
message.setRaw(encodedEmail)
return message
}
谢谢你!看起来像是正确的做法。测试它。 –
完全合作!谢谢! –
@LevRatinov甜! :) 很高兴我能帮上忙。作为一个便笺, – Tholle