use of javax.mail.util.ByteArrayDataSource in project aws-doc-sdk-examples by awsdocs.
the class SendMessages method send.
public void send(byte[] attachment, String emailAddress) throws MessagingException, IOException {
MimeMessage message = null;
Session session = Session.getDefaultInstance(new Properties());
// Create a new MimeMessage object.
message = new MimeMessage(session);
// Add subject, from and to lines.
message.setSubject(subject, "UTF-8");
message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress));
// Create a multipart/alternative child container.
MimeMultipart msgBody = 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(bodyText, "text/plain; charset=UTF-8");
// Define the HTML part.
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(bodyHTML, "text/html; charset=UTF-8");
// Add the text and HTML parts to the child container.
msgBody.addBodyPart(textPart);
msgBody.addBodyPart(htmlPart);
// Add the child container to the wrapper object.
wrap.setContent(msgBody);
// 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 ByteArrayDataSource(attachment, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
att.setDataHandler(new DataHandler(fds));
String reportName = "VideoReport.xls";
att.setFileName(reportName);
// Add the attachment to the message.
msg.addBodyPart(att);
// Try to send the email.
try {
System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
Region region = Region.US_WEST_2;
SesClient client = SesClient.builder().credentialsProvider(EnvironmentVariableCredentialsProvider.create()).region(region).build();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());
byte[] arr = new byte[buf.remaining()];
buf.get(arr);
SdkBytes data = SdkBytes.fromByteArray(arr);
RawMessage rawMessage = RawMessage.builder().data(data).build();
SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder().rawMessage(rawMessage).build();
client.sendRawEmail(rawEmailRequest);
} catch (SesException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("Email sent with attachment");
}
use of javax.mail.util.ByteArrayDataSource in project aws-doc-sdk-examples by awsdocs.
the class SendMessages method send.
public void send(byte[] attachment, String emailAddress) throws MessagingException, IOException {
MimeMessage message = null;
Session session = Session.getDefaultInstance(new Properties());
// Create a new MimeMessage object.
message = new MimeMessage(session);
// Add subject, from and to lines.
message.setSubject(subject, "UTF-8");
message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress));
// Create a multipart/alternative child container.
MimeMultipart msgBody = 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(bodyText, "text/plain; charset=UTF-8");
// Define the HTML part.
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(bodyHTML, "text/html; charset=UTF-8");
// Add the text and HTML parts to the child container.
msgBody.addBodyPart(textPart);
msgBody.addBodyPart(htmlPart);
// Add the child container to the wrapper object.
wrap.setContent(msgBody);
// 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 ByteArrayDataSource(attachment, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
att.setDataHandler(new DataHandler(fds));
String reportName = "WorkReport.xls";
att.setFileName(reportName);
// Add the attachment to the message.
msg.addBodyPart(att);
// Try to send the email.
try {
System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
Region region = Region.US_WEST_2;
SesClient client = SesClient.builder().credentialsProvider(EnvironmentVariableCredentialsProvider.create()).region(region).build();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());
byte[] arr = new byte[buf.remaining()];
buf.get(arr);
SdkBytes data = SdkBytes.fromByteArray(arr);
RawMessage rawMessage = RawMessage.builder().data(data).build();
SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder().rawMessage(rawMessage).build();
client.sendRawEmail(rawEmailRequest);
} catch (SesException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("Email sent with attachment");
}
use of javax.mail.util.ByteArrayDataSource in project stanbol by apache.
the class MessageBodyReaderUtils method fromMultipart.
/**
* Returns content parsed from {@link MediaType#MULTIPART_FORM_DATA}.
* It iterates over all {@link BodyPart}s and tries to create {@link RequestData}
* instances. In case the {@link BodyPart#getContentType()} is not present or
* can not be parsed, the {@link RequestData#getMediaType()} is set to
* <code>null</code>. If {@link BodyPart#getInputStream()} is not defined an
* {@link IllegalArgumentException} is thrown. The {@link BodyPart#getFileName()}
* is used for {@link RequestData#getName()}. The ordering of the returned
* Content instances is the same as within the {@link MimeMultipart} instance
* parsed from the input stream. <p>
* This Method does NOT load the data into memory, but returns directly the
* {@link InputStream}s as returned by the {@link BodyPart}s. Therefore
* it is saved to be used with big attachments.<p>
* This Method is necessary because within {@link MessageBodyReader} one
* can not use the usual annotations as used within Resources. so this method
* allows to access the data directly from the parameters available from the
* {@link MessageBodyReader#readFrom(Class, Type, java.lang.annotation.Annotation[], MediaType, javax.ws.rs.core.MultivaluedMap, InputStream)}
* method<p>
* To test this Method with curl use:
* <code><pre>
* curl -v -X POST -F "content=@{dataFile};type={mimeType}"
* {serviceURL}
* </pre></code>
* Note that between {contentParam} and the datafile MUST NOT be a '='!
* @param mimeData the mime encoded data
* @param mediaType the mediaType (parsed to the {@link ByteArrayDataSource}
* constructor)
* @return the contents parsed from the {@link BodyPart}s
* @throws IOException an any Exception while reading the stream or
* {@link MessagingException} exceptions other than {@link ParseException}s
* @throws IllegalArgumentException If a {@link InputStream} is not available
* for any {@link BodyPart} or on {@link ParseException}s while reading the
* MimeData from the stream.
*/
public static List<RequestData> fromMultipart(InputStream mimeData, MediaType mediaType) throws IOException, IllegalArgumentException {
ByteArrayDataSource ds = new ByteArrayDataSource(mimeData, mediaType.toString());
List<RequestData> contents = new ArrayList<RequestData>();
try {
MimeMultipart data = new MimeMultipart(ds);
// For now search the first bodypart that fits and only debug the others
for (int i = 0; i < data.getCount(); i++) {
BodyPart bp = data.getBodyPart(i);
String fileName = bp.getFileName();
MediaType mt;
try {
mt = bp.getContentType() != null ? MediaType.valueOf(bp.getContentType()) : null;
} catch (IllegalArgumentException e) {
log.warn(String.format("Unable to parse MediaType form Mime Bodypart %s: " + " fileName %s | Disposition %s | Description %s", i + 1, fileName, bp.getDisposition(), bp.getDescription()), e);
mt = null;
}
InputStream stream = bp.getInputStream();
if (stream == null) {
throw new IllegalArgumentException(String.format("Unable to get InputStream for Mime Bodypart %s: " + "mediaType %s fileName %s | Disposition %s | Description %s", i + 1, fileName, bp.getDisposition(), bp.getDescription()));
} else {
contents.add(new RequestData(mt, bp.getFileName(), stream));
}
}
} catch (ParseException e) {
throw new IllegalStateException(String.format("Unable to parse data from %s request", MediaType.MULTIPART_FORM_DATA_TYPE), e);
} catch (MessagingException e) {
throw new IOException("Exception while reading " + MediaType.MULTIPART_FORM_DATA_TYPE + " request", e);
}
return contents;
}
use of javax.mail.util.ByteArrayDataSource in project cxf by apache.
the class AttachmentSerializerTest method doTestMessageWrite.
private void doTestMessageWrite(boolean xop, String soapContentType) throws Exception {
MessageImpl msg = new MessageImpl();
Collection<Attachment> atts = new ArrayList<>();
AttachmentImpl a = new AttachmentImpl("test.xml");
InputStream is = getClass().getResourceAsStream("my.wav");
ByteArrayDataSource ds = new ByteArrayDataSource(is, "application/octet-stream");
a.setDataHandler(new DataHandler(ds));
atts.add(a);
msg.setAttachments(atts);
// Set the SOAP content type
msg.put(Message.CONTENT_TYPE, soapContentType);
final String soapCtType;
final String soapCtParams;
final String soapCtParamsEscaped;
int p = soapContentType.indexOf(';');
if (p != -1) {
soapCtParams = soapContentType.substring(p);
soapCtParamsEscaped = escapeQuotes(soapCtParams);
soapCtType = soapContentType.substring(0, p);
} else {
soapCtParams = "";
soapCtParamsEscaped = "";
soapCtType = soapContentType;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
msg.setContent(OutputStream.class, out);
AttachmentSerializer serializer = new AttachmentSerializer(msg);
if (!xop) {
// default is "on"
serializer.setXop(xop);
}
serializer.writeProlog();
// we expect the following rules at the package header level
// - the package header must have media type multipart/related.
// - the start-info property must be present for mtom but otherwise optional. its
// value must contain the content type associated with the root content's xml serialization,
// including its parameters as appropriate.
// - the action property should not appear directly in the package header level
// - the type property must contain the media type type/subtype of the root content part.
// namely application/xop+xml for mtom but otherwise text/xml or application/soap+xml
// depending on the soap version 1.1 or 1.2, respectively.
String ct = (String) msg.get(Message.CONTENT_TYPE);
assertTrue(ct.indexOf("multipart/related;") == 0);
assertTrue(ct.indexOf("start=\"<root.message@cxf.apache.org>\"") > -1);
assertTrue(ct.indexOf("start-info=\"" + soapCtType + soapCtParamsEscaped + "\"") > -1);
assertTrue(ct.indexOf("action=\"") == -1);
if (xop) {
assertTrue(ct.indexOf("type=\"application/xop+xml\"") > -1);
} else {
assertTrue(ct.indexOf("type=\"" + soapCtType + "\"") > -1);
}
out.write("<soap:Body/>".getBytes());
serializer.writeAttachments();
out.flush();
DataSource source = new ByteArrayDataSource(new ByteArrayInputStream(out.toByteArray()), ct);
MimeMultipart mpart = new MimeMultipart(source);
Session session = Session.getDefaultInstance(new Properties());
MimeMessage inMsg = new MimeMessage(session);
inMsg.setContent(mpart);
inMsg.addHeaderLine("Content-Type: " + ct);
MimeMultipart multipart = (MimeMultipart) inMsg.getContent();
MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(0);
// - the action must appear if it was present in the original message (i.e., for soap 1.2)
if (xop) {
assertEquals("application/xop+xml; charset=UTF-8; type=\"" + soapCtType + soapCtParamsEscaped + "\"", part.getHeader("Content-Type")[0]);
} else {
assertEquals(soapCtType + "; charset=UTF-8" + soapCtParams, part.getHeader("Content-Type")[0]);
}
assertEquals("binary", part.getHeader("Content-Transfer-Encoding")[0]);
assertEquals("<root.message@cxf.apache.org>", part.getHeader("Content-ID")[0]);
InputStream in = part.getDataHandler().getInputStream();
ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
IOUtils.copy(in, bodyOut);
out.close();
in.close();
assertEquals("<soap:Body/>", bodyOut.toString());
MimeBodyPart part2 = (MimeBodyPart) multipart.getBodyPart(1);
assertEquals("application/octet-stream", part2.getHeader("Content-Type")[0]);
assertEquals("binary", part2.getHeader("Content-Transfer-Encoding")[0]);
assertEquals("<test.xml>", part2.getHeader("Content-ID")[0]);
}
use of javax.mail.util.ByteArrayDataSource in project cxf by apache.
the class WrappedAttachmentsTest method testCreateAndModify.
@Test
public void testCreateAndModify() {
Map<String, DataHandler> content = new HashMap<>();
content.put("att-1", new DataHandler(new ByteArrayDataSource("Hello world!".getBytes(), "text/plain")));
content.put("att-2", new DataHandler(new ByteArrayDataSource("Hola mundo!".getBytes(), "text/plain")));
WrappedAttachments attachments = new WrappedAttachments(content);
Attachment att3 = new AttachmentImpl("att-3", new DataHandler(new ByteArrayDataSource("Bonjour tout le monde!".getBytes(), "text/plain")));
assertEquals(2, attachments.size());
assertFalse(attachments.isEmpty());
assertTrue(attachments.containsAll(attachments));
List<String> testCollection = new ArrayList<>();
testCollection.add("Some value");
assertFalse(attachments.containsAll(testCollection));
attachments.add(att3);
assertEquals(3, attachments.size());
attachments.add(att3);
assertEquals(3, attachments.size());
attachments.remove(att3);
assertEquals(2, attachments.size());
Attachment attx = attachments.iterator().next();
attachments.remove(attx);
assertEquals(1, attachments.size());
// NOPMD - explicitly test this
Attachment[] atts = attachments.toArray(new Attachment[0]);
assertEquals(1, atts.length);
assertEquals("att-1".equals(attx.getId()) ? "att-2" : "att-1", atts[0].getId());
// NOPMD - explicitly test this
atts = attachments.toArray(new Attachment[attachments.size()]);
assertEquals(1, atts.length);
assertEquals("att-1".equals(attx.getId()) ? "att-2" : "att-1", atts[0].getId());
// NOPMD - explicitly test this
Object[] o = attachments.toArray();
assertEquals(1, o.length);
Attachment a = (Attachment) o[0];
assertEquals("att-1".equals(attx.getId()) ? "att-2" : "att-1", a.getId());
attachments.clear();
assertTrue(attachments.isEmpty());
assertTrue(content.isEmpty());
}
Aggregations