通过亚马逊在Java中发送带有附件的电子邮件的例子 [英] Example of sending an email with attachment via Amazon in Java

查看:423
本文介绍了通过亚马逊在Java中发送带有附件的电子邮件的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有发送电子邮件,带有附件,通过亚马逊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){...}
  }
}

这篇关于通过亚马逊在Java中发送带有附件的电子邮件的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆