Skip to content

Commit 7464dd4

Browse files
committed
Adds a JavaMail example which sends Text, HTML and Attachment with the SparkPost transmission API
1 parent c06a101 commit 7464dd4

File tree

11 files changed

+474
-4
lines changed

11 files changed

+474
-4
lines changed

apps/pom.xml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
<?xml version="1.0" encoding="UTF-8"?>
2-
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3-
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
43
<parent>
54
<groupId>com.sparkpost</groupId>
65
<artifactId>sparkpost</artifactId>
@@ -14,5 +13,6 @@
1413
<modules>
1514
<module>sparkpost-samples-app</module>
1615
<module>sparkpost-documentor-app</module>
17-
</modules>
18-
</project>
16+
<module>sparkpost-javamail-app</module>
17+
</modules>
18+
</project>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<FindBugsFilter>
2+
3+
<Match>
4+
<!-- Reason for exclusion: This is code from a third party. -->
5+
<Class name="org.slf4j.impl.StaticLoggerBinder" />
6+
</Match>
7+
8+
<Match>
9+
<!-- Reason for exclusion: All bugs in test classes, except for JUnit-specific
10+
bugs -->
11+
<Class name="~.*\.*Test" />
12+
<Not>
13+
<Bug code="IJU" />
14+
</Not>
15+
</Match>
16+
<Match>
17+
<!-- Reason for exclusion: This is sample code and this part is not expected to be reused. -->
18+
<Class name="~.*\.SparkPostBaseApp" />
19+
<Not>
20+
<Bug code="DM_EXIT" />
21+
</Not>
22+
</Match>
23+
24+
</FindBugsFilter>
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/target/
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
##
2+
# The URL to use for the SparkPost API If empty default will be used
3+
##
4+
#SPARKPOST_BASE_URL=https://api.sparkpost.com/api/v1/
5+
6+
7+
##
8+
# This your API key for SparkPost
9+
##
10+
SPARKPOST_API_KEY=YOUR SPARKPOST API KEY
11+
12+
13+
##
14+
# Username and password for SparkPost API
15+
# You should use API Key instead if possible
16+
##
17+
#USERNAME=
18+
#PASSWORD=
19+
20+
21+
##
22+
# The subject that will be put into templates
23+
# When messages are sent
24+
##
25+
SPARKPOST_SUBJECT=This is a sample subject
26+
27+
28+
##
29+
#
30+
##
31+
SPARKPOST_SENDER_EMAIL=noreply@example.com
32+
33+
34+
##
35+
#
36+
##
37+
SPARKPOST_FROM=from_address@example.com
38+
39+
40+
##
41+
#
42+
# SPARKPOST_RECIPIENTS
43+
# A comma delimited list of email addresses to send to
44+
#
45+
# Example: recipient_one@example.com, recipient_two@example.com
46+
##
47+
SPARKPOST_RECIPIENTS=recipient_one@example.com, recipient_two@example.com
48+
49+
28.1 KB
Binary file not shown.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?xml version="1.0" encoding="UTF-8" ?>
2+
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
3+
4+
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
5+
<appender name="console" class="org.apache.log4j.ConsoleAppender">
6+
<param name="Target" value="System.out"/>
7+
<layout class="org.apache.log4j.PatternLayout">
8+
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
9+
</layout>
10+
</appender>
11+
12+
<root>
13+
<priority value ="debug" />
14+
<appender-ref ref="console" />
15+
</root>
16+
17+
</log4j:configuration>
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?xml version="1.0"?>
2+
<project
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
4+
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
5+
<modelVersion>4.0.0</modelVersion>
6+
<parent>
7+
<groupId>com.sparkpost</groupId>
8+
<artifactId>apps</artifactId>
9+
<version>0.10</version>
10+
</parent>
11+
<groupId>com.sparkpost.sample</groupId>
12+
<artifactId>sparkpost-javamail-app</artifactId>
13+
<version>1.0-SNAPSHOT</version>
14+
<name>sparkpost-javamail-app</name>
15+
<url>http://maven.apache.org</url>
16+
<dependencies>
17+
<dependency>
18+
<groupId>com.sparkpost</groupId>
19+
<artifactId>sparkpost-lib</artifactId>
20+
</dependency>
21+
<dependency>
22+
<groupId>javax.mail</groupId>
23+
<artifactId>javax.mail-api</artifactId>
24+
<version>1.5.5</version>
25+
</dependency>
26+
<dependency>
27+
<groupId>com.sun.mail</groupId>
28+
<artifactId>javax.mail</artifactId>
29+
<version>1.5.3</version>
30+
</dependency>
31+
<dependency>
32+
<groupId>org.apache.commons</groupId>
33+
<artifactId>commons-io</artifactId>
34+
<version>1.3.2</version>
35+
</dependency>
36+
37+
<dependency>
38+
<groupId>junit</groupId>
39+
<artifactId>junit</artifactId>
40+
<scope>test</scope>
41+
</dependency>
42+
</dependencies>
43+
</project>
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
package com.sparkpost.sample;
2+
3+
import java.io.ByteArrayOutputStream;
4+
import java.io.IOException;
5+
import java.io.UnsupportedEncodingException;
6+
import java.util.ArrayList;
7+
import java.util.HashMap;
8+
import java.util.List;
9+
import java.util.Map;
10+
import java.util.Properties;
11+
12+
import javax.activation.DataHandler;
13+
import javax.activation.DataSource;
14+
import javax.activation.FileDataSource;
15+
import javax.mail.Message;
16+
import javax.mail.MessagingException;
17+
import javax.mail.Multipart;
18+
import javax.mail.Session;
19+
import javax.mail.internet.MimeBodyPart;
20+
import javax.mail.internet.MimeMessage;
21+
import javax.mail.internet.MimeMultipart;
22+
23+
import org.apache.log4j.Level;
24+
import org.apache.log4j.Logger;
25+
26+
import com.sparkpost.Client;
27+
import com.sparkpost.exception.SparkPostException;
28+
import com.sparkpost.model.AddressAttributes;
29+
import com.sparkpost.model.RecipientAttributes;
30+
import com.sparkpost.model.TemplateContentAttributes;
31+
import com.sparkpost.model.TransmissionWithRecipientArray;
32+
import com.sparkpost.model.responses.Response;
33+
import com.sparkpost.resources.ResourceTransmissions;
34+
import com.sparkpost.sample.helpers.SparkPostBaseApp;
35+
import com.sparkpost.transport.RestConnection;
36+
37+
/**
38+
* This demonstration of using JavaMail mime message with the SparkPosts REST API
39+
*/
40+
public class App extends SparkPostBaseApp {
41+
42+
public static void main(String[] args) throws Exception {
43+
Logger.getRootLogger().setLevel(Level.DEBUG);
44+
45+
App app = new App();
46+
app.runApp();
47+
}
48+
49+
private void runApp() throws Exception {
50+
51+
Message message = createMultipartMessage();
52+
53+
// Convert JavaMail message into a string for transmission
54+
String rfc822Content = getMessageAsString(message);
55+
56+
// Add in a TO and a From field that will be populated from SparkPost substitution data
57+
rfc822Content = "To: {{address.email}}\r\nFrom: {{from}}\r\n" + rfc822Content;
58+
59+
// Loads an email to send from the file system
60+
String fromAddress = getFromAddress();
61+
String[] recipients = getTestRecipients();
62+
63+
sendEmail(fromAddress, recipients, rfc822Content);
64+
65+
}
66+
67+
private void sendEmail(String from, String[] recipients, String email) throws SparkPostException, IOException {
68+
Client sparkpostClient = newConfiguredClient();
69+
70+
TransmissionWithRecipientArray transmission = new TransmissionWithRecipientArray();
71+
72+
// Populate Recipients
73+
List<RecipientAttributes> recipientArray = new ArrayList<RecipientAttributes>();
74+
for (String recipient : recipients) {
75+
RecipientAttributes recipientAttribs = new RecipientAttributes();
76+
recipientAttribs.setAddress(new AddressAttributes(recipient));
77+
recipientArray.add(recipientAttribs);
78+
}
79+
transmission.setRecipientArray(recipientArray);
80+
81+
transmission.setReturnPath(from);
82+
83+
// Populate Substitution Data
84+
Map<String, String> substitutionData = new HashMap<String, String>();
85+
substitutionData.put("from", from);
86+
87+
// SparkPost will set fields in HTML and/or Plain parts with the value here
88+
// See: https://developers.sparkpost.com/api/#/introduction/substitutions-reference
89+
substitutionData.put("name", "Your Name Here");
90+
91+
transmission.setSubstitutionData(substitutionData);
92+
93+
// Populate Email Body
94+
TemplateContentAttributes contentAttributes = new TemplateContentAttributes();
95+
contentAttributes.setEmailRFC822(email);
96+
transmission.setContentAttributes(contentAttributes);
97+
98+
// Send the Email
99+
RestConnection connection = new RestConnection(sparkpostClient, getEndPoint());
100+
101+
Response response = ResourceTransmissions.create(connection, 0, transmission);
102+
if (response.getResponseCode() == 200) {
103+
// Message successfully sent
104+
System.out.println("Transmission Response: " + response);
105+
} else {
106+
// An error occurred
107+
System.err.println("TRANSMISSION ERROR: " + response);
108+
}
109+
}
110+
111+
/**
112+
* Builds an email with a text, HTML, and attachment part
113+
*
114+
* @return a JavaMail message
115+
* @throws MessagingException
116+
*/
117+
private Message createMultipartMessage() throws MessagingException {
118+
Properties props = new Properties();
119+
// This is not used but we have to set it for JavaMail to create the
120+
// message
121+
props.put("mail.smtp.host", "none");
122+
123+
Session session = Session.getDefaultInstance(props, null);
124+
Message message = new MimeMessage(session);
125+
126+
message.setSubject("A multipart mime message demo");
127+
128+
Multipart multiPart = new MimeMultipart("alternative");
129+
130+
// Create at text part
131+
MimeBodyPart textPart = new MimeBodyPart();
132+
textPart.setText("{{name}},\r\nplain text content", "utf-8");
133+
134+
// Build HTML part of email
135+
MimeBodyPart htmlPart = new MimeBodyPart();
136+
htmlPart.setContent("<b>{{name}},<br><br>Our HTML content</b>", "text/html; charset=utf-8");
137+
138+
// Put all the parts together
139+
multiPart.addBodyPart(textPart);
140+
multiPart.addBodyPart(htmlPart);
141+
message.setContent(multiPart);
142+
143+
// Add an attachment to email
144+
MimeBodyPart attachmentPart = new MimeBodyPart();
145+
146+
String filename = "java_SparkPost_background.pdf";
147+
DataSource source = new FileDataSource(filename);
148+
attachmentPart.setDataHandler(new DataHandler(source));
149+
attachmentPart.setFileName(filename);
150+
multiPart.addBodyPart(attachmentPart);
151+
152+
return message;
153+
}
154+
155+
/**
156+
* Turn a JavaMail message into RFC822 content
157+
*
158+
* @param msg
159+
* the message that will be converted
160+
* @return RFC822 content
161+
* @throws MessagingException
162+
* @throws IOException
163+
*/
164+
private String getMessageAsString(Message msg) throws IOException, MessagingException {
165+
String content = "";
166+
ByteArrayOutputStream out = new ByteArrayOutputStream();
167+
try {
168+
msg.writeTo(out);
169+
content = new String(out.toByteArray(), "UTF-8");
170+
return content;
171+
172+
} catch (UnsupportedEncodingException e) {
173+
// This should never happen
174+
e.printStackTrace();
175+
} finally {
176+
try {
177+
out.close();
178+
} catch (IOException e) {
179+
e.printStackTrace();
180+
}
181+
}
182+
183+
// Fail
184+
return null;
185+
}
186+
}

0 commit comments

Comments
 (0)