English 中文(简体)
如何使用 aws ses 和 java 发送带有文件附件的电子邮件?
原标题:How to send email with a file attachment using aws ses and java?

我检查了所有 Aws 文档, 但没有找到任何实例或文字, 可以指导“ 如何使用 aws ses( 简单的电子邮件服务) 和 java 发送带有文件附件的电子邮件 ”?

我需要写出符合逻辑的文字:

  • Receive a set of data
  • convert this data to CSV file
  • Create a file e.g. abc.csv
  • Prepare a email body, add this attachment and text
  • Send it

I have followed below examples, these explains the process something like this: Example: enter image description here
Image Source: http://www.codejava.net/java-ee/javamail/send-e-mail-with-attachment-in-java

我听了这个答案 ,但不明白这部分:

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

这个例子也跟随了这个例子:https://mintylishjava.blogspot.in/2014/05/example-of-sending-email-with-mulpal.html

但我不明白:

   DataSource source = new FileDataSource(filename);

      attachment.setDataHandler(new DataHandler(source));

< 加固> 如何定义源, 如果我正在准备一个相同函数 的文件, 例如 。

File myFile = new File("TestFile_"+ LocalDateTime.now().toString()+ ".csv");

        try {
            fop = new FileOutputStream(myFile);

            byte[] contentInBytes = textBody.getData().getBytes();

            fop.write(contentInBytes);
            fop.flush();
            fop.close();
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }

无法确定我到底错过了什么? < / 坚固>


Solved

Below 函数,我为解决这一问题写了信(于2016年12月29日至2016年12月29日添加):

public String sendReceivedOutputAsEmailToUsers(EmailProperties emailProperties,String fileContents , String toEmails) throws InternalErrorException
    {
        String[] toAddressesInput = null;
        // Get the toArrays
        toAddressesInput = toEmails.split(",");

        BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(PropertyManager.getSetting("awsAccessKeyId"),
                PropertyManager.getSetting("awsSecretAccessKey"));

        // Construct an object to contain the recipient address.
        Destination destination = new Destination().withToAddresses(toAddressesInput);


        // Create the subject and body of the message.
        // emailRequest.getSubject() - need to write the format of message

        // Prepare Subject
        String subject = CommonStrings.defaultSubject + " Generated at: " + LocalDateTime.now().toString();

        if(emailProperties.getSubject()!=null)
        {
           subject =  emailProperties.getSubject() + " Generated at: " + LocalDateTime.now().toString();;
        }
        String inputFileName = null;

        if(emailProperties.getAttachmentName() != null)
        {
            inputFileName = emailProperties.getAttachmentName() + "_" + LocalDateTime.now().toString() + ".csv";

        }else
        {
            inputFileName = "GenreatedReport__" + LocalDateTime.now().toString() + ".csv";
        }

        Content textBody = null;
        FileOutputStream fop = null;

        if(emailProperties.getIsBody().equalsIgnoreCase("true"))
        {
            if(emailProperties.getBodyMessagePrefix()!= null) {
                textBody = new Content().withData("

" + emailProperties.getBodyMessagePrefix() + "

" +fileContents);
            } else
            {
                textBody = new Content().withData("

" +fileContents);
            }

        }

        AmazonSimpleEmailServiceClient client = null;
        client = new AmazonSimpleEmailServiceClient(basicAWSCredentials);

        Properties props = new Properties();
        // sets SMTP server properties
        props.setProperty("mail.transport.protocol", "aws");
        props.setProperty("mail.aws.user", PropertyManager.getSetting("awsAccessKeyId"));
        props.setProperty("mail.aws.password",  PropertyManager.getSetting("awsSecretAccessKey"));

        Session mailSession = Session.getInstance(props);

        // Create an email
        MimeMessage msg = new MimeMessage(mailSession);

        // Sender and recipient
        try {
            msg.setFrom(new InternetAddress(CommonStrings.adminEmailAddress));
        } catch (MessagingException e) {
            throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
        }

        // msg.setRecipient( Message.RecipientType.TO, new InternetAddress("abc  <[email protected]>"));

        // for multiple Recipient
        InternetAddress[] toAddresses = new InternetAddress[toAddressesInput.length];
        for (int i = 0; i < toAddresses.length; i++)
        {
            try {
                toAddresses[i] = new InternetAddress(toAddressesInput[i]);
            } catch (AddressException e) {
                throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
            }
        }
        try {
            msg.setRecipients(javax.mail.Message.RecipientType.TO, toAddresses);
            msg.setSubject(subject);
        } catch (MessagingException e) {
            throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());

        }

        // creates message part
        BodyPart part = new MimeBodyPart();

        try {
            part.setContent(textBody.getData(), "text/html");
        } catch (MessagingException e) {
            throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
        }

        // Add a MIME part to the message
        MimeMultipart mp = new MimeMultipart();
        try {
            mp.addBodyPart(part);
        } catch (MessagingException e) {
            throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
        }
        BodyPart attachment = null;
        attachment = new MimeBodyPart();

        try {
            DataSource source = new FileDataSource(fileContents);
            attachment.setDataHandler(new DataHandler(source));
            attachment.setText(fileContents);
            attachment.setFileName(inputFileName);
            mp.addBodyPart(attachment);
            msg.setContent(mp);
        } catch (MessagingException e) {
            throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
        }

        // Print the raw email content on the console
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            msg.writeTo(out);
        } catch (IOException e) {
            throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
        } catch (MessagingException e) {
            throw new InternalErrorException(ExceptionStrings.EX_EMAIL + ":" + e.getMessage());
        }

        // Send Mail
        RawMessage rm = new RawMessage();
        rm.setData(ByteBuffer.wrap(out.toString().getBytes()));
        client.sendRawEmail(new SendRawEmailRequest().withRawMessage(rm));

        logger.info("email sent : success");
        return "success";
    }
}
问题回答

您可以通过 v2 API 做到这一点。

    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage message = new MimeMessage(session);
    message.setSubject("Test Email with Attachment");

    MimeMultipart multipart = new MimeMultipart();

    // Body part
    MimeBodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("This is the email body.");
    multipart.addBodyPart(textBodyPart);

    // Attachment part
    MimeBodyPart attachmentPart = new MimeBodyPart();
    DataSource source = new ByteArrayDataSource("Example attachment content".getBytes(), "application/octet-stream");
    attachmentPart.setDataHandler(new javax.activation.DataHandler(source));
    attachmentPart.setFileName("example.txt");
    multipart.addBodyPart(attachmentPart);

    message.setContent(multipart);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    message.writeTo(outputStream);
    ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());

    RawMessage rawMessage = new RawMessage(buf);


    SendEmailRequest emailRequest = SendEmailRequest.builder()
        .content(EmailContent.builder().raw(rawMessage).build())
        .build();

    SendEmailResponse resp = sesV2Client.sendEmail(emailRequest);

AWS对此有一些文件,但没有提到 v2 API:https://docs.aws.amazon.com/ses/latst/dg/send-email-raw.html





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签