Sunday, July 8, 2012

Email with Attachments via Spring and SendGrid (Part 2)

Review

In the previous section, we have laid down the functional specs and took a preview of the application. In this section, we will write and discuss the Java classes and the project's structure.


Project Structure

Our application is a Maven project which means it follows the Maven convention for web applications.

Here's a preview of our project's structure:



Domain Layer

The domain layer contains a Message class that represents an email message and n UploadedFile class that represents a file upload.




Controller Layer

The controller layer contains a simple controller EmailController that serves a form for composing and sending emails. It has two main methods: send for sending emails and upload for uploading files.

Whenever a file is attached and uploaded, it is saved first to a temporary location which can be retrieved later via its filename. When the send method is triggered, it basically pulls out the file from the temporary location based on the filename.


Service Layer

The service layer contains the email service. We have a simple interface EmailService for sending messages.


The actual implementation SendGridEmailService relies on RestTemplate to send the email message via HTTP.


How did we manage to produce this code? Basically this is a translation of SendGrid's API using Spring RestTemplate. The specific SendGrid API we're using is the Mail module, which is under the Web API. Please see http://docs.sendgrid.com/documentation/api/web-api/mail/#send for the complete documentation.

To test the Mail module, you can either use your browser or CURL (if you're familiar with it).

Browser-based test:
https://sendgrid.com/api/mail.send.xml?api_user=youremail@domain.com&api_key=secureSecret&to=destination@example.com&toname=Destination&subject=Example%20Subject&text=testingtextbody&from=info@domain.com

CURL-based test:
curl -d 'to=destination@example.com&toname=Destination&subject=Example Subject&text=testingtextbody&from=info@domain.com&api_user=sendgridUsername&api_key=sendgridPassword' https://sendgrid.com/api/mail.send.json

Utility Layer

This layer contains helper classes and interfaces. Here we've extracted the required SendGrid parameters when sending emails via HTTP.


Next

We've just completed discussing and writing our Java classes. In the next section, we will declare the required configuration files. Click here to proceed.

StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Email with Attachments via Spring and SendGrid (Part 2) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

1 comment: