我没有找到任何有关配置GlassFish的JavaMail以使用Amazon SES发送电子邮件的明确文档。有人可以提供一个例子吗?
答案 0 :(得分:3)
在AWS JDK内,您可以找到以下示例:samples \ AmazonSimpleEmailService \ AWSJavaMailSample.java
基本上,您需要将协议设置为" aws",以及AWS凭证的用户和密码:
/*
* Setup JavaMail to use the Amazon Simple Email Service by specifying
* the "aws" protocol.
*/
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "aws");
/*
* Setting mail.aws.user and mail.aws.password are optional. Setting
* these will allow you to send mail using the static transport send()
* convince method. It will also allow you to call connect() with no
* parameters. Otherwise, a user name and password must be specified
* in connect.
*/
props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
props.setProperty("mail.aws.password", credentials.getAWSSecretKey());
为了发送消息:
// Create a email session
Session session = Session.getInstance(props);
// Create a new Message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(FROM));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
msg.setSubject(SUBJECT);
msg.setText(BODY);
msg.saveChanges();
// Reuse one Transport object for sending all your messages
// for better performance
Transport t = new AWSJavaMailTransport(session, null);
t.connect();
t.sendMessage(msg, null);
那应该为你做好工作。
答案 1 :(得分:2)
您可以让Glassfish提供JavaMail会话,从而允许您的应用程序代码与提供程序无关。
使用Glassfish管理界面创建JavaMail会话:
资源 - > JavaMail会话。
关键属性是:
表单还需要“默认用户”的值,但据我所知,它不会被使用。
此外,您需要将以下属性添加到会话中:
您的应用程序代码可以通过注入获取会话:
@Resource(name="mail/somevalue")
private Session mailSession;
使用注入的会话发送电子邮件
Message msg = new MimeMessage(mailSession);
try {
msg.setSubject(subject);
msg.setText(body);
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
msg.setFrom();
Transport t = session.getTransport();
if (!t.isConnected()) {
t.connect();
}
t.sendMessage(msg, null);
} catch (MessagingException ex) {
// Handle exception
} catch (UnsupportedEncodingException ex) {
// Handle exception
}
对 msg.setFrom()的调用将使用会话属性“mail.user”中保存的值填充消息的From字段,该字段取自JavaMail会话字段“Default发件人地址“