2

我没有找到任何关于配置 GlassFish 的 JavaMail 以使用 Amazon SES 发送电子邮件的明确文档。有人可以提供一个例子吗?

4

2 回答 2

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);

那应该为你做这项工作。

于 2012-02-13T20:06:27.597 回答
2

您可以让 Glassfish 提供 JavaMail 会话,从而使您的应用程序代码与提供者无关。

使用 Glassfish 管理界面创建 JavaMail 会话:

资源->JavaMail 会话。

关键属性是:

  • JNDI:邮件/某个值
  • 邮件主机:email.us-east-1.amazonaws.com
  • 默认发件人地址:源电子邮件地址
  • 传输协议:aws
  • 传输协议类:com.amazonaws.services.simpleemail.AWSJavaMailTransport

该表单还需要“默认用户”的值,但据我所知,它不会被使用。

此外,您需要将以下属性添加到会话中:

  • mail.aws.password:您的 AWS 密钥
  • mail.aws.user:您的 AWS 访问密钥

您的应用程序代码可以通过注入获取 Session:

@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 会话字段“默认发件人地址”

于 2012-06-13T22:13:50.853 回答