Search code examples
amazon-web-servicesaws-sdkaws-pinpoint

AWS-Pinpoint email notification with attachment not working


I am trying to do a POC in which i am using aws pinpoint to send email. Simple email is working fine but when i am trying to send email with attachment, i am not able to identify what is the correct way. In the documentation this link is describes what need to do

https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_RawMessage.html

Below is the code i found on various websites:

        // Create a new email client
        AmazonPinpointEmail client = AmazonPinpointEmailClientBuilder.standard()
                .withRegion(region).build();

        // Combine all of the components of the email to create a request.
        SendEmailRequest request = new SendEmailRequest()
                .withFromEmailAddress(senderAddress)
                .withConfigurationSetName(configurationSet)
                .withDestination(new Destination()
                        .withToAddresses(toAddresses)
                        .withCcAddresses(ccAddresses)
                        .withBccAddresses(bccAddresses)
                )
                .withContent(new EmailContent()
                        .withRaw(new RawMessage().withData())
                        //the withData takes type buffer, how to create a message which contains attachement.
        client.sendEmail(request);
        System.out.println("Email sent!");
        System.out.println(request);

Anyone used this api to send attachment, please help in creating message which contains attachment, subject and body. Thanks


Solution

  • To send emails with attachment using Amazon PinpointEmail you'll need (for simplicity) :

    • JavaMail Library : an API that is used to compose, write and read electronic messages by utilizing classes like BodyPart, MimeBodyPart e.t.c

    Below is a sample java code snippet that I have tested to be working :

        Session session = Session.getDefaultInstance(new Properties());
    
        // Create a new MimeMessage object.
        MimeMessage message = new MimeMessage(session);
    
        // Add subject, from and to lines.
        message.setSubject(subject, "UTF-8");
        message.setFrom(new InternetAddress(senderAddress));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
    
        // Create a multipart/alternative child container.
        MimeMultipart msg_body = new MimeMultipart("alternative");
    
        // Create a wrapper for the HTML and text parts.        
        MimeBodyPart wrap = new MimeBodyPart();
    
        // Define the text part.
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");
    
        // Define the HTML part.
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(BODY_HTML,"text/html; charset=UTF-8");
    
        // Add the text and HTML parts to the child container.
        msg_body.addBodyPart(textPart);
        msg_body.addBodyPart(htmlPart);
    
        // Add the child container to the wrapper object.
        wrap.setContent(msg_body);
    
        // Create a multipart/mixed parent container.
        MimeMultipart msg = new MimeMultipart("mixed");
    
        // Add the parent container to the message.
        message.setContent(msg);
    
        // Add the multipart/alternative part to the message.
        msg.addBodyPart(wrap);
    
        // Define the attachment
        MimeBodyPart att = new MimeBodyPart();
        DataSource fds = new FileDataSource(ATTACHMENT);
        att.setDataHandler(new DataHandler(fds));
        att.setFileName(fds.getName());
    
        // Add the attachment to the message.
        msg.addBodyPart(att);
    
        // Try to send the email.
        try {
    
            System.out.println("===============================================");
    
            System.out.println("Getting Started with Amazon PinpointEmail"
                    +"using the AWS SDK for Java...");
            System.out.println("===============================================\n");
    
    
            // Instantiate an Amazon PinpointEmail client, which will make the service call with the supplied AWS credentials.
            AmazonPinpointEmail client = AmazonPinpointEmailClientBuilder.standard()
                .withRegion(Regions.US_EAST_1).build();
    
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            message.writeTo(outputStream);
    
                  SendEmailRequest rawEmailRequest = new SendEmailRequest()
                          .withFromEmailAddress(senderAddress)
                          .withDestination(new Destination()
                              .withToAddresses(toAddress)
                          )
                          .withContent(new EmailContent()
                                  .withRaw(new RawMessage().withData(ByteBuffer.wrap(outputStream.toByteArray())))
                          );
    
            client.sendEmail(rawEmailRequest);
    
            System.out.println("Email sent!");
            // Display an error if something goes wrong.
        } catch (Exception ex) {
            System.out.println("Email Failed");
            System.err.println("Error message: " + ex.getMessage());
            ex.printStackTrace();
        }
    

    The above code can be summarized in 6 steps:

    1. Get session
    2. Create MimeBodyPart object
    3. Create MimeMultiPart object
    4. Create datasource (defining the attachment)
    5. Add parts to MimeMultiPart
    6. Send the email through AmazonPinpointEmail API

    You can find the complete code in github

    Hope this helps.