通过亚马逊在Java中发送带有附件的电子邮件的例子亚马逊、例子、附件、电子邮件

由网友(北染)分享简介:有没有人有发送电子邮件,带有附件,通过亚马逊SES(在Java中)?Does anyone have an example of sending an email, with an attachment, via Amazon SES (in Java)?推荐答案也许有点晚了,但你可以使用这个code(你还需要J...

有没有人有发送电子邮件,带有附件,通过亚马逊SES(在Java中)?

Does anyone have an example of sending an email, with an attachment, via Amazon SES (in Java)?

推荐答案

也许有点晚了,但你可以使用这个code(你还需要Java邮件):

Maybe a little bit late, but you can use this code (you also need 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){...}
  }
}
阅读全文

相关推荐

最新文章