在Java中通过Amazon发送带附件的电子邮件的示例

时间:2011-11-01 07:07:32

标签: java email amazon-web-services

是否有人通过Amazon SES(Java)发送带附件的电子邮件示例?

4 个答案:

答案 0 :(得分:14)

也许有点晚了,但你可以使用这段代码(你还需要Java Mail):

public class MailSender
{
      private Transport AWSTransport;
      ...
      //Initialize transport
      private void initAWSTransport() throws MessagingException
      {
        String keyID = <your key id>
        String secretKey = <your secret key>
        MailAWSCredentials credentials = new MailAWSCredentials();
        credentials.setCredentials(keyID, secretKey);
        AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(credentials);
        Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "aws");
        props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
        props.setProperty("mail.aws.password", credentials.getAWSSecretKey());
        AWSsession = Session.getInstance(props);
        AWStransport = new AWSJavaMailTransport(AWSsession, null);
        AWStransport.connect();
      }

  public void sendEmail(byte[] attachment)
  {
    //mail properties
    String senderAddress = <Sender address>;
    String recipientAddress = <Recipient address>;
    String subject = <Mail subject>;
    String text = <Your text>;
    String mimeTypeOfText = <MIME type of text part>;
    String fileMimeType = <MIME type of your attachment>;
    String fileName = <Name of attached file>;

    initAWSTransport();

    try
    {
      // Create new message
      Message msg = new MimeMessage(AWSsession);
      msg.setFrom(new InternetAddress(senderAddress));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress));
      msg.setSubject(subject);

      //Text part
      Multipart multipart = new MimeMultipart();
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setContent(text, mimeTypeOfText);
      multipart.addBodyPart(messageBodyPart);

      //Attachment part
      if (attachment != null && attachment.length != 0)
      {
        messageBodyPart = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(attachment,fileMimeType);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileName);
        multipart.addBodyPart(messageBodyPart);
      }
      msg.setContent(multipart);

      //send message
      msg.saveChanges();
      AWSTransport.sendMessage(msg, null);
    } catch (MessagingException e){...}
  }
}

答案 1 :(得分:13)

也许有点晚了。 替代使用Java Mail和Amazon Raw Mail Sender发送邮件

public static void sendMail(String subject, String message, byte[] attachement, String fileName, String contentType, String from, String[] to) {
    try {
        // JavaMail representation of the message
        Session s = Session.getInstance(new Properties(), null);
        MimeMessage mimeMessage = new MimeMessage(s);

        // Sender and recipient
        mimeMessage.setFrom(new InternetAddress(from));
        for (String toMail : to) {
            mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toMail));
        }

        // Subject
        mimeMessage.setSubject(subject);

        // Add a MIME part to the message
        MimeMultipart mimeBodyPart = new MimeMultipart();
        BodyPart part = new MimeBodyPart();
        part.setContent(message, MediaType.TEXT_HTML);
        mimeBodyPart.addBodyPart(part);

        // Add a attachement to the message
        part = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(attachement, contentType);
        part.setDataHandler(new DataHandler(source));
        part.setFileName(fileName);
        mimeBodyPart.addBodyPart(part);

        mimeMessage.setContent(mimeBodyPart);

        // Create Raw message
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        mimeMessage.writeTo(outputStream);
        RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));

        // Credentials
        String keyID = "";// <your key id>
        String secretKey = "";// <your secret key>
        AWSCredentials credentials = new BasicAWSCredentials(keyID, secretKey);
        AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials);

        // Send Mail
        SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
        rawEmailRequest.setDestinations(Arrays.asList(to));
        rawEmailRequest.setSource(from);
        client.sendRawEmail(rawEmailRequest);

    } catch (IOException | MessagingException e) {
        // your Exception
        e.printStackTrace();
    }
}

答案 2 :(得分:0)

这是带有日志记录并检查生产情况的更新后的清理版本。

public void sendEmail(String to, String subject, String body, String attachment, String mimeType, String fileName) {
    if (to == null) return;

    String environment = System.getProperty("ENVIRONMENT", System.getenv("ENVIRONMENT"));
    String logMessage;
    if (environment != null && environment.equals("production")) {
        logMessage = "Sent email to " + to + ".";
    } else {
        to = "success@simulator.amazonses.com";
        logMessage = "Email sent to success@simulator.amazonses.com because $ENVIRONMENT != 'production'";
    }

    // https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-raw-using-sdk.html
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage message = new MimeMessage(session);
    try {
        message.setSubject(subject, "UTF-8");
        message.setFrom(new InternetAddress(FROM));
        message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
            MimeMultipart msg = new MimeMultipart("mixed");
                MimeBodyPart wrap = new MimeBodyPart();
                    MimeMultipart msgBody = new MimeMultipart("alternative");
                        MimeBodyPart textPart = new MimeBodyPart();
                        MimeBodyPart htmlPart = new MimeBodyPart();
                        textPart.setContent(body, "text/plain; charset=UTF-8");
                        htmlPart.setContent(body,"text/html; charset=UTF-8");
                    msgBody.addBodyPart(textPart);
                    msgBody.addBodyPart(htmlPart);
                wrap.setContent(msgBody);
            msg.addBodyPart(wrap);
                MimeBodyPart att = new MimeBodyPart();
                att.setDataHandler(new DataHandler(attachment, mimeType));
                att.setFileName(fileName);
//                  DataSource fds = new FileDataSource(attachment);
//                  att.setDataHandler(new DataHandler(fds));
//                  att.setFileName(fds.getName());
            msg.addBodyPart(att);
        message.setContent(msg);

        AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder
                .standard().withRegion(Regions.US_EAST_1).build();
        message.writeTo(System.out);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        message.writeTo(outputStream);
        RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
        SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
//                      .withConfigurationSetName(CONFIGURATION_SET);
        client.sendRawEmail(rawEmailRequest);
        Logger.info(this.getClass(), "sendEmail()", logMessage);
    } catch (Exception ex) {
        Logger.info(this.getClass(), "sendEmail()", "The email was not sent. Error: " + ex.getMessage());
    }
}

https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-raw-using-sdk.html

  

您使用共享凭证文件来传递您的AWS访问密钥ID和秘密访问密钥。作为使用共享凭证文件的替代方法,您可以通过设置两个环境变量(分别为AWS_ACCESS_KEY_ID和AWS_SECRET_ACCESS_KEY)来指定AWS访问密钥ID和秘密访问密钥。

答案 3 :(得分:0)

https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html有一个示例,它同时发送html和文本正文(当然带有附件)。 FWIW,这是其Java代码到Kotlin的转换和重组。依赖性为'com.sun.mail:javax.mail:1.6.2'

data class Attachment(val fileName: String, val contentType: String, val data: ByteArray)

fun sendEmailWithAttachment(from: String, to: List<String>, subject: String, htmlBody: String, textBody: String,
                            attachment: Attachment) {
    try {
        val textPart = MimeBodyPart().apply {
            setContent(textBody, "text/plain; charset=UTF-8")
        }

        val htmlPart = MimeBodyPart().apply {
            setContent(htmlBody, "text/html; charset=UTF-8")
        }

        // Create a multipart/alternative child container.
        val childPart = MimeMultipart("alternative").apply {
            // Add the text and HTML parts to the child container.
            addBodyPart(textPart)
            addBodyPart(htmlPart)
        }

        // Create a wrapper for the HTML and text parts.
        val childWrapper = MimeBodyPart().apply {
            setContent(childPart)
        }

        // Define the attachment
        val dataSource = ByteArrayDataSource(attachment.data, attachment.contentType)
        // val dataSource = FileDataSource(filePath)  // if using file directly
        val attPart = MimeBodyPart().apply {
            dataHandler = DataHandler(dataSource)
            fileName = attachment.fileName
        }

        // Create a multipart/mixed parent container.
        val parentPart = MimeMultipart("mixed").apply {
            // Add the multipart/alternative part to the message.
            addBodyPart(childWrapper)
            addBodyPart(attPart)  // Add the attachment to the message.
        }

        // JavaMail representation of the message
        val s = Session.getDefaultInstance(Properties())
        val mimeMessage = MimeMessage(s).apply {
            // Add subject, from and to lines
            this.subject = subject
            setFrom(InternetAddress(from))
            to.forEach() {
                addRecipient(javax.mail.Message.RecipientType.TO, InternetAddress(it))
            }

            // Add the parent container to the message.
            setContent(parentPart)
        }

        // Create Raw message
        val rawMessage = with(ByteArrayOutputStream()) {
            mimeMessage.writeTo(this)
            RawMessage(ByteBuffer.wrap(this.toByteArray()))
        }

        val rawEmailRequest = SendRawEmailRequest(rawMessage).apply {
            source = from
            setDestinations(to)
        }

        // Send Mail
        val client = AmazonSimpleEmailServiceClientBuilder.standard()
                .withRegion(Regions.US_EAST_1).build()
        client.sendRawEmail(rawEmailRequest)
        println("Email with attachment sent to $to")
    } catch (e: Exception) {
        println(e)
    }
}