Skip to content

Commit 1d37d07

Browse files
committed
Merge pull request #29 from SparkPost/feature/issue_26_attachments
Feature/issue 26 attachments
2 parents c0e66bd + 26bfb18 commit 1d37d07

File tree

15 files changed

+239
-35
lines changed

15 files changed

+239
-35
lines changed

README.md

+14-13
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ The SparkPost Java Library is available in this [Maven Repository](http://maven.
2323
<dependency>
2424
<groupId>com.sparkpost</groupId>
2525
<artifactId>sparkpost-lib</artifactId>
26-
<version>0.13</version>
26+
<version>0.14</version>
2727
</dependency>
2828
```
2929

@@ -59,7 +59,7 @@ public class SparkPost {
5959

6060
## Advanced Send Email Example
6161

62-
With SparkPost you have complete control over all aspects of an email and a powerful tempting solution.
62+
With SparkPost you have complete control over all aspects of an email and a powerful templating solution.
6363

6464
```java
6565

@@ -75,17 +75,18 @@ private void sendEmail(String from, String[] recipients, String email) throws Sp
7575
}
7676
transmission.setRecipientArray(recipientArray);
7777

78-
transmission.setReturnPath(from);
79-
80-
// Populate Substitution Data
81-
Map<String, String> substitutionData = new HashMap<String, String>();
82-
substitutionData.put("from", from);
83-
transmission.setSubstitutionData(substitutionData);
84-
85-
// Populate Email Body
86-
TemplateContentAttributes contentAttributes = new TemplateContentAttributes();
87-
contentAttributes.setEmailRFC822(email);
88-
transmission.setContentAttributes(contentAttributes);
78+
// Populate Substitution Data
79+
Map<String, Object> substitutionData = new HashMap<String, Object>();
80+
substitutionData.put("yourContent", "You can add substitution data too.");
81+
transmission.setSubstitutionData(substitutionData);
82+
83+
// Populate Email Body
84+
TemplateContentAttributes contentAttributes = new TemplateContentAttributes();
85+
contentAttributes.setFrom(new AddressAttributes(from));
86+
contentAttributes.setSubject("Your subject content here. {{yourContent}}");
87+
contentAttributes.setText("Your Text content here. {{yourContent}}");
88+
contentAttributes.setHtml("<p>Your <b>HTML</b> content here. {{yourContent}}</p>");
89+
transmission.setContentAttributes(contentAttributes);
8990

9091
// Send the Email
9192
RestConnection connection = new RestConnection(client, getEndPoint());

apps/pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<parent>
44
<groupId>com.sparkpost</groupId>
55
<artifactId>sparkpost</artifactId>
6-
<version>0.13</version>
6+
<version>0.14</version>
77
</parent>
88
<modelVersion>4.0.0</modelVersion>
99
<artifactId>apps</artifactId>

apps/sparkpost-documentor-app/pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<parent>
55
<groupId>com.sparkpost</groupId>
66
<artifactId>apps</artifactId>
7-
<version>0.13</version>
7+
<version>0.14</version>
88
</parent>
99
<artifactId>sparkpost-documentor-app</artifactId>
1010
<name>Generates Markdown of Protocol</name>

apps/sparkpost-javamail-app/pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<parent>
77
<groupId>com.sparkpost</groupId>
88
<artifactId>apps</artifactId>
9-
<version>0.13</version>
9+
<version>0.14</version>
1010
</parent>
1111
<groupId>com.sparkpost.sample</groupId>
1212
<artifactId>sparkpost-javamail-app</artifactId>

apps/sparkpost-samples-app/pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<parent>
55
<groupId>com.sparkpost</groupId>
66
<artifactId>apps</artifactId>
7-
<version>0.13</version>
7+
<version>0.14</version>
88
</parent>
99
<artifactId>sparkpost-samples-app</artifactId>
1010
<name>Example use SparkPost library</name>

apps/sparkpost-samples-app/src/main/java/com/sparkpost/samples/SendEmailSample.java

+9-7
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,14 @@ private void runApp() throws SparkPostException, IOException {
3838
this.client = this.newConfiguredClient();
3939

4040
// Loads an email to send from the file system
41-
String template = getTemplate("sample_sp_email.eml");
4241
String fromAddress = getFromAddress();
4342
String[] recipients = getTestRecipients();
4443

45-
sendEmail(fromAddress, recipients, template);
44+
sendEmail(fromAddress, recipients);
4645

4746
}
4847

49-
private void sendEmail(String from, String[] recipients, String email) throws SparkPostException {
48+
private void sendEmail(String from, String[] recipients) throws SparkPostException {
5049
TransmissionWithRecipientArray transmission = new TransmissionWithRecipientArray();
5150

5251
// Populate Recipients
@@ -58,16 +57,19 @@ private void sendEmail(String from, String[] recipients, String email) throws Sp
5857
}
5958
transmission.setRecipientArray(recipientArray);
6059

61-
transmission.setReturnPath(from);
62-
6360
// Populate Substitution Data
6461
Map<String, Object> substitutionData = new HashMap<String, Object>();
65-
substitutionData.put("from", from);
62+
substitutionData.put("yourContent", "You can add substitution data too.");
6663
transmission.setSubstitutionData(substitutionData);
6764

6865
// Populate Email Body
6966
TemplateContentAttributes contentAttributes = new TemplateContentAttributes();
70-
contentAttributes.setEmailRFC822(email);
67+
contentAttributes.setFrom(new AddressAttributes(from));
68+
contentAttributes.setSubject("Your subject content here. {{yourContent}}");
69+
contentAttributes.setText("Your Text content here. {{yourContent}}");
70+
contentAttributes.setHtml("<p>Your <b>HTML</b> content here. {{yourContent}}</p>");
71+
transmission.setContentAttributes(contentAttributes);
72+
7173
transmission.setContentAttributes(contentAttributes);
7274

7375
// Send the Email
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
2+
package com.sparkpost.samples;
3+
4+
import java.io.IOException;
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
import org.apache.log4j.Level;
9+
import org.apache.log4j.Logger;
10+
11+
import com.sparkpost.Client;
12+
import com.sparkpost.exception.SparkPostException;
13+
import com.sparkpost.model.AddressAttributes;
14+
import com.sparkpost.model.AttachmentAttributes;
15+
import com.sparkpost.model.InlineImageAttributes;
16+
import com.sparkpost.model.RecipientAttributes;
17+
import com.sparkpost.model.TemplateContentAttributes;
18+
import com.sparkpost.model.TransmissionWithRecipientArray;
19+
import com.sparkpost.model.responses.Response;
20+
import com.sparkpost.resources.ResourceTransmissions;
21+
import com.sparkpost.sdk.samples.helpers.SparkPostBaseApp;
22+
import com.sparkpost.transport.RestConnection;
23+
24+
public class SendEmailWithFilesSample extends SparkPostBaseApp {
25+
26+
static final Logger logger = Logger.getLogger(CreateTemplateSimple.class);
27+
28+
private Client client;
29+
30+
public static void main(String[] args) throws SparkPostException, IOException {
31+
Logger.getRootLogger().setLevel(Level.DEBUG);
32+
33+
SendEmailWithFilesSample sample = new SendEmailWithFilesSample();
34+
sample.runApp();
35+
}
36+
37+
private void runApp() throws SparkPostException, IOException {
38+
this.client = this.newConfiguredClient();
39+
40+
// Loads an email to send from the file system
41+
String fromAddress = getFromAddress();
42+
String[] recipients = getTestRecipients();
43+
44+
sendEmail(fromAddress, recipients);
45+
46+
}
47+
48+
private void sendEmail(String from, String[] recipients) throws SparkPostException {
49+
TransmissionWithRecipientArray transmission = new TransmissionWithRecipientArray();
50+
51+
// Populate Recipients
52+
List<RecipientAttributes> recipientArray = new ArrayList<RecipientAttributes>();
53+
for (String recipient : recipients) {
54+
RecipientAttributes recipientAttribs = new RecipientAttributes();
55+
recipientAttribs.setAddress(new AddressAttributes(recipient));
56+
recipientArray.add(recipientAttribs);
57+
}
58+
transmission.setRecipientArray(recipientArray);
59+
60+
// Populate Email Body
61+
TemplateContentAttributes contentAttributes = new TemplateContentAttributes();
62+
contentAttributes.setFrom(new AddressAttributes(from));
63+
contentAttributes.setSubject("Hello World");
64+
contentAttributes.setText("Simple text content");
65+
66+
// Add a text attachment
67+
AttachmentAttributes attachment = new AttachmentAttributes();
68+
attachment.setName("aFile.txt");
69+
attachment.setType("text/plain; charset=UTF-8;");
70+
// This is Base64 of the file contents
71+
attachment.setData("SGVsbG8gV29ybGQhCuydvA==");
72+
List<AttachmentAttributes> attachments = new ArrayList<>();
73+
attachments.add(attachment);
74+
contentAttributes.setAttachments(attachments);
75+
76+
// Add inline image
77+
InlineImageAttributes image = new InlineImageAttributes();
78+
/*
79+
* The name of the inline image, which will be inserted into the Content-ID header.
80+
* The image should be referenced in your HTML content using <img src="cid:THIS_NAME">.
81+
* The name must be unique within the content.inline_images array.
82+
*/
83+
contentAttributes.setHtml("<p>My fantastic HTML content.<br><br><b>SparkPost</b> <img src=\"cid:AnImage.png\"></p>");
84+
image.setName("AnImage.png");
85+
image.setType("image/png");
86+
// This is Base64 of the file contents
87+
image.setData(
88+
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAAlwSFlzAAAWJQAAFiUBSVIk8AAAAXxJREFUOBFjvJVg84P5718WBjLAX2bmPyxMf/+xMDH8YyZDPwPDXwYGJkIaOXTNGdiUtHAqI2jA/18/GUQzGsg3gMfKg4FVQo6BiYcPqyF4XcChaczA4+DP8P//f4b/P3+SZgAzvxCDSGYjAyMjI8PvZw+AoYXdLuyiQLtE0uoZWAREwLb+fnKXQTipkngXcJu7MnACQx8G2FX1GHgs3bDGBlYX8HlFM/z9+JbhzewWhmf1CQyfti9j+PfzBwO/ZxTMTDiNmQKBfmZX1GB42V/K8P38YbDCX/dvMDAwMzPwuYbBNcIYmC4AhfjvXwx/376AqQHTf96+ZPj34xuKGIiDaQBQ8PPBTQwCoZkMjJzcYA3MgqIMAr7xDJ/3rAHzkQnGO7FWf5gZ/qLmBSZmBoHgNAZee1+Gf18/MzCyczJ83LyQ4fPetch6Gf4xMP3FbgBMGdAgJqAr/n37zABMTTBROA0ygAWUJUG5Civ4B8xwX78CpbD6FJiHmf4AAFicbTMTr5jAAAAAAElFTkSuQmCC");
89+
List<InlineImageAttributes> inlineImages = new ArrayList<InlineImageAttributes>();
90+
inlineImages.add(image);
91+
contentAttributes.setInlineImages(inlineImages);
92+
93+
transmission.setContentAttributes(contentAttributes);
94+
95+
// Send the Email
96+
RestConnection connection = new RestConnection(this.client, getEndPoint());
97+
Response response = ResourceTransmissions.create(connection, 0, transmission);
98+
99+
logger.debug("Transmission Response: " + response);
100+
}
101+
102+
}

libs/pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<parent>
55
<groupId>com.sparkpost</groupId>
66
<artifactId>sparkpost</artifactId>
7-
<version>0.13</version>
7+
<version>0.14</version>
88
</parent>
99
<modelVersion>4.0.0</modelVersion>
1010
<artifactId>libs</artifactId>

libs/sparkpost-lib/pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<parent>
55
<groupId>com.sparkpost</groupId>
66
<artifactId>libs</artifactId>
7-
<version>0.13</version>
7+
<version>0.14</version>
88
</parent>
99
<!-- <version>0.10</version> -->
1010
<artifactId>sparkpost-lib</artifactId>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
2+
package com.sparkpost.model;
3+
4+
import lombok.Data;
5+
import lombok.EqualsAndHashCode;
6+
7+
/**
8+
* DTO for a transmission of attachments.
9+
*/
10+
@Data
11+
@EqualsAndHashCode(callSuper = true)
12+
public class AttachmentAttributes extends FileAttributes {
13+
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
2+
package com.sparkpost.model;
3+
4+
import com.yepher.jsondoc.annotations.Description;
5+
6+
import lombok.Data;
7+
import lombok.EqualsAndHashCode;
8+
9+
/**
10+
* DTO for attachments and inline images
11+
*/
12+
@Data
13+
@EqualsAndHashCode(callSuper = true)
14+
public class FileAttributes extends Base {
15+
16+
public FileAttributes() {
17+
18+
}
19+
20+
/**
21+
* Valid email address
22+
*/
23+
@Description(
24+
value = "The MIME type of the file. The value will apply \"as-is\" to the \"Content-Type\" header of the generated MIME part for the file.",
25+
sample = {"image/jpeg"})
26+
private String type;
27+
28+
/**
29+
* User-friendly name for the email address
30+
*/
31+
@Description(value = "The name of the file.", sample = {"rainbow.jpg"})
32+
private String name;
33+
34+
/**
35+
* Email address to display in the "To" header instead of address.email (for BCC)
36+
*/
37+
@Description(
38+
value = "he content of the file as a Base64 encoded string. The string should not contain \\r\\n line breaks. The SparkPost systems will add line breaks as necessary to ensure the Base64 encoded lines contain no more than 76 characters each.",
39+
sample = {""})
40+
private String data;
41+
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
2+
package com.sparkpost.model;
3+
4+
import lombok.Data;
5+
import lombok.EqualsAndHashCode;
6+
7+
/**
8+
* DTO for a transmission of inline images.
9+
*/
10+
@Data
11+
@EqualsAndHashCode(callSuper = true)
12+
public class InlineImageAttributes extends FileAttributes {
13+
14+
}

libs/sparkpost-lib/src/main/java/com/sparkpost/model/TemplateContentAttributes.java

+15-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11

22
package com.sparkpost.model;
33

4+
import java.util.List;
45
import java.util.Map;
56

67
import com.google.gson.annotations.SerializedName;
@@ -59,9 +60,22 @@ public class TemplateContentAttributes extends Base {
5960
@Description(value = "Extra email headers to send", sample = {"Dictionary of Email Headers"})
6061
private Map<String, String> headers = null;
6162

63+
/**
64+
* Attachments for a transmission
65+
*/
66+
@Description(value = "List of AttachmentAttributes. Attachments are not valid with templateId.", sample = {""})
67+
private List<AttachmentAttributes> attachments = null;
68+
69+
/**
70+
* Inline images for a transmission
71+
*/
72+
@Description(value = "List of InlineImageAttributes. Inline images are not valid with templateId.", sample = {""})
73+
@SerializedName("inline_images")
74+
private List<InlineImageAttributes> inlineImages = null;
75+
6276
/**
6377
* Alternatively, the email_rfc822 may be used *instead* of all the other fields.
64-
* The email_rfc822 field is mutually exclusive with all of the above fields.
78+
* The email_rfc822 field is mutually exclusive with all of the other fields in this class.
6579
*/
6680
@Description(
6781
value = "Alternatively, the email_rfc822 may be used *instead* of all the other fields. The email_rfc822 field is mutually exclusive with all of the above fields.",

libs/sparkpost-lib/src/main/java/com/sparkpost/transport/RestConnection.java

+21-6
Original file line numberDiff line numberDiff line change
@@ -169,12 +169,9 @@ private HttpURLConnection createConnectionObject(String path, Method method) thr
169169
// Send HTTP data (payload) to server
170170
private void sendData(HttpURLConnection conn, String data) throws SparkPostException {
171171
byte[] bytes = null;
172-
try
173-
{
172+
try {
174173
bytes = data.getBytes(DEFAULT_CHARSET);
175-
}
176-
catch (UnsupportedEncodingException e)
177-
{
174+
} catch (UnsupportedEncodingException e) {
178175
// This should never happen. UTF-8 should always be available but we
179176
// have to catch it so pass it on if it fails.
180177
throw new SparkPostException(e);
@@ -247,10 +244,28 @@ private Response receiveResponse(HttpURLConnection conn, Response response) thro
247244
// an error.
248245
response.setResponseBody("");
249246
} catch (IOException ex) {
247+
String line = "";
248+
try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(), DEFAULT_CHARSET))) {
249+
250+
while ((line = rd.readLine()) != null) {
251+
sb.append(line);
252+
}
253+
254+
response.setResponseBody(sb.toString());
255+
response.setRequestId(conn.getHeaderField("X-SparkPost-Request-Id"));
256+
257+
logger.error("Server Response:\n" + sb.toString() + "\n");
258+
259+
} catch (IOException ex2) {
260+
// Ignore we are going to throw an exception anyway
261+
}
262+
if (logger.isDebugEnabled()) {
263+
logger.error("Server Response:" + response);
264+
}
250265
throw new SparkPostException("Error reading server response: " + ex.toString() + ": " + sb.toString() + "(" + response.getResponseMessage() + ")");
251266
}
252-
253267
return response;
268+
254269
}
255270

256271
// This method actually performs an HTTP request.

0 commit comments

Comments
 (0)