use of javax.mail.internet.MimeMultipart in project voldemort by voldemort.
the class GetAllResponseSender method sendResponse.
/**
* Sends nested multipart response. Outer multipart wraps all the keys
* requested. Each key has a separate multipart for the versioned values.
*/
@Override
public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception {
/*
* Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.
* However when writing to the outputStream we only send the multiPart object and not the entire
* mimeMessage. This is intentional.
*
* In the earlier version of this code we used to create a multiPart object and just send that multiPart
* across the wire.
*
* However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates
* a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated
* immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the
* enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()
* on the body part. It's this updateHeaders call that transfers the content type from the
* DataHandler to the part's MIME Content-Type header.
*
* To make sure that the Content-Type headers are being updated (without changing too much code), we decided
* to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.
* This is to make sure multiPart's headers are updated accurately.
*/
MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
// multiPartKeys is the outer multipart
MimeMultipart multiPartKeys = new MimeMultipart();
ByteArrayOutputStream keysOutputStream = new ByteArrayOutputStream();
for (Entry<ByteArray, List<Versioned<byte[]>>> entry : versionedResponses.entrySet()) {
ByteArray key = entry.getKey();
String base64Key = RestUtils.encodeVoldemortKey(key.get());
String contentLocationKey = "/" + this.storeName + "/" + base64Key;
// Create the individual body part - for each key requested
MimeBodyPart keyBody = new MimeBodyPart();
try {
// Add the right headers
keyBody.addHeader(CONTENT_TYPE, "application/octet-stream");
keyBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
keyBody.addHeader(CONTENT_LOCATION, contentLocationKey);
} catch (MessagingException me) {
logger.error("Exception while constructing key body headers", me);
keysOutputStream.close();
throw me;
}
// multiPartValues is the inner multipart
MimeMultipart multiPartValues = new MimeMultipart();
for (Versioned<byte[]> versionedValue : entry.getValue()) {
byte[] responseValue = versionedValue.getValue();
VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
String eTag = RestUtils.getSerializedVectorClock(vectorClock);
numVectorClockEntries += vectorClock.getVersionMap().size();
// Create the individual body part - for each versioned value of
// a key
MimeBodyPart valueBody = new MimeBodyPart();
try {
// Add the right headers
valueBody.addHeader(CONTENT_TYPE, "application/octet-stream");
valueBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
valueBody.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);
valueBody.setContent(responseValue, "application/octet-stream");
valueBody.addHeader(RestMessageHeaders.CONTENT_LENGTH, Integer.toString(responseValue.length));
multiPartValues.addBodyPart(valueBody);
} catch (MessagingException me) {
logger.error("Exception while constructing value body part", me);
keysOutputStream.close();
throw me;
}
}
try {
// Add the inner multipart as the content of the outer body part
keyBody.setContent(multiPartValues);
multiPartKeys.addBodyPart(keyBody);
} catch (MessagingException me) {
logger.error("Exception while constructing key body part", me);
keysOutputStream.close();
throw me;
}
}
message.setContent(multiPartKeys);
message.saveChanges();
try {
multiPartKeys.writeTo(keysOutputStream);
} catch (Exception e) {
logger.error("Exception while writing mutipart to output stream", e);
throw e;
}
ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
responseContent.writeBytes(keysOutputStream.toByteArray());
// Create the Response object
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
// Set the right headers
response.setHeader(CONTENT_TYPE, "multipart/binary");
response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
// Copy the data into the payload
response.setContent(responseContent);
response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
// Write the response to the Netty Channel
if (logger.isDebugEnabled()) {
String keyStr = getKeysHexString(this.versionedResponses.keySet());
debugLog("GET_ALL", this.storeName, keyStr, startTimeInMs, System.currentTimeMillis(), numVectorClockEntries);
}
this.messageEvent.getChannel().write(response);
if (performanceStats != null && isFromLocalZone) {
recordStats(performanceStats, startTimeInMs, Tracked.GET_ALL);
}
keysOutputStream.close();
}
use of javax.mail.internet.MimeMultipart in project SpringStepByStep by JavaProgrammerLB.
the class SendHTMLEmailWithTemplate method main.
public static void main(String[] args) throws Exception {
Properties props = new Properties();
try {
props.load(new FileInputStream(new File("settings.properties")));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "******");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("Testing Subject");
BodyPart body = new MimeBodyPart();
// freemarker stuff.
Configuration cfg = new Configuration();
Template template = cfg.getTemplate("html-mail-template.ftl");
Map<String, String> rootMap = new HashMap<String, String>();
rootMap.put("to", "liubei");
rootMap.put("body", "Sample html email using freemarker");
rootMap.put("from", "liubei");
Writer out = new StringWriter();
template.process(rootMap, out);
// freemarker stuff ends.
/* you can add html tags in your text to decorate it. */
body.setContent(out.toString(), "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
body = new MimeBodyPart();
String filename = "hello.txt";
DataSource source = new FileDataSource(filename);
body.setDataHandler(new DataHandler(source));
body.setFileName(filename);
multipart.addBodyPart(body);
message.setContent(multipart, "text/html;charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("Done....");
}
use of javax.mail.internet.MimeMultipart in project SpringStepByStep by JavaProgrammerLB.
the class SendAttachmentInEmail method main.
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "destinationemail@gmail.com";
// Sender's email ID needs to be mentioned
String from = "fromemail@gmail.com";
//change accordingly
final String username = "manishaspatil";
//change accordingly
final String password = "******";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "/home/manisha/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
use of javax.mail.internet.MimeMultipart in project zm-mailbox by Zimbra.
the class ParseMimeMessage method parseMimeMsgSoap.
/**
* Given an {@code <m>} element from SOAP, return us a parsed {@link MimeMessage}, and also fill in the
* {@link MimeMessageData} structure with information we parsed out of it (e.g. contained Invite, msgids, etc etc)
*
* @param msgElem the {@code <m>} element
* @param additionalParts MimeBodyParts that we want to have added to the {@link MimeMessage} (ie things the server
* is adding onto the message)
* @param inviteParser Callback which handles {@code <inv>} embedded invite components
* @param out Holds info about things we parsed out of the message that the caller might want to know about
*/
public static MimeMessage parseMimeMsgSoap(ZimbraSoapContext zsc, OperationContext octxt, Mailbox mbox, Element msgElem, MimeBodyPart[] additionalParts, InviteParser inviteParser, MimeMessageData out, boolean attachMessageFromCache) throws ServiceException {
// msgElem == "<m>" E_MSG
assert (msgElem.getName().equals(MailConstants.E_MSG));
Account target = DocumentHandler.getRequestedAccount(zsc);
ParseMessageContext ctxt = new ParseMessageContext();
ctxt.out = out;
ctxt.zsc = zsc;
ctxt.octxt = octxt;
ctxt.mbox = mbox;
ctxt.use2231 = target.isPrefUseRfc2231();
ctxt.defaultCharset = target.getPrefMailDefaultCharset();
if (Strings.isNullOrEmpty(ctxt.defaultCharset)) {
ctxt.defaultCharset = MimeConstants.P_CHARSET_UTF8;
}
try {
MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSmtpSession(target));
MimeMultipart mmp = null;
Element partElem = msgElem.getOptionalElement(MailConstants.E_MIMEPART);
Element attachElem = msgElem.getOptionalElement(MailConstants.E_ATTACH);
Element inviteElem = msgElem.getOptionalElement(MailConstants.E_INVITE);
boolean hasContent = (partElem != null || inviteElem != null || additionalParts != null);
// || inviteElem != null || additionalParts!=null);
boolean isMultipart = (attachElem != null);
if (isMultipart) {
// may need to change to "digest" later
mmp = new ZMimeMultipart("mixed");
mm.setContent(mmp);
}
// Grab the <inv> part now so we can stick it in a multipart/alternative if necessary
MimeBodyPart[] alternatives = null;
if (inviteElem != null) {
int additionalLen = 0;
if (additionalParts != null) {
additionalLen += additionalParts.length;
}
alternatives = new MimeBodyPart[additionalLen + 1];
int curAltPart = 0;
// goes into the "content" subpart
InviteParserResult result = inviteParser.parse(zsc, octxt, mbox.getAccount(), inviteElem);
if (partElem != null && result.mCal != null) {
// If textual content is provided and there's an invite,
// set the text as DESCRIPTION of the iCalendar. This helps
// clients that ignore alternative text content and only
// displays the DESCRIPTION specified in the iCalendar part.
// (e.g. MS Entourage for Mac)
String desc = getTextPlainContent(partElem);
String html = getTextHtmlContent(partElem);
result.mCal.addDescription(desc, html);
if (result.mInvite != null) {
// It's possible the notes were given in <inv> node only, with no corresponding MIME parts.
if ((desc != null && desc.length() > 0) || (html != null && html.length() > 0)) {
result.mInvite.setDescription(desc, html);
if (desc != null && desc.length() > 0) {
result.mInvite.setFragment(Fragment.getFragment(desc, true));
}
}
}
}
MimeBodyPart mbp = CalendarMailSender.makeICalIntoMimePart(result.mCal);
alternatives[curAltPart++] = mbp;
if (additionalParts != null) {
for (int i = 0; i < additionalParts.length; i++) {
alternatives[curAltPart++] = additionalParts[i];
}
}
} else {
alternatives = additionalParts;
}
// handle the content from the client, if any
if (hasContent) {
setContent(mm, mmp, partElem != null ? partElem : inviteElem, alternatives, ctxt);
}
// attachments go into the toplevel "mixed" part
if (isMultipart && attachElem != null) {
handleAttachments(attachElem, mmp, ctxt, null, Part.ATTACHMENT, attachMessageFromCache);
}
// <m> attributes: id, f[lags], s[ize], d[ate], cid(conv-id), l(parent folder)
// <m> child elements: <e> (email), <s> (subject), <f> (fragment), <mp>, <attach>
MessageAddresses maddrs = new MessageAddresses();
Set<String> headerNames = ImmutableSet.copyOf(Provisioning.getInstance().getConfig().getCustomMimeHeaderNameAllowed());
for (Element elem : msgElem.listElements()) {
String eName = elem.getName();
if (eName.equals(MailConstants.E_ATTACH)) {
// ignore it...
} else if (eName.equals(MailConstants.E_MIMEPART)) {
/* <mp> */
// processMessagePart(mm, elem);
} else if (eName.equals(MailConstants.E_EMAIL)) {
/* <e> */
maddrs.add(elem, ctxt.defaultCharset);
} else if (eName.equals(MailConstants.E_IN_REPLY_TO)) {
/* <irt> */
// mm.setHeader("In-Reply-To", elem.getText());
} else if (eName.equals(MailConstants.E_SUBJECT)) {
/* <su> */
// mm.setSubject(elem.getText(), "utf-8");
} else if (eName.equals(MailConstants.E_FRAG)) {
/* <f> */
ZimbraLog.soap.debug("Ignoring message fragment data");
} else if (eName.equals(MailConstants.E_INVITE)) {
/* <inv> */
// Already processed above. Ignore it.
} else if (eName.equals(MailConstants.E_CAL_TZ)) {
/* <tz> */
// Ignore as a special case.
} else if (eName.equals(MailConstants.E_HEADER)) {
// <h>
String name = elem.getAttribute(MailConstants.A_NAME);
if (headerNames.contains(name)) {
mm.addHeader(name, MimeHeader.escape(elem.getText(), Charsets.UTF_8, true));
} else {
throw ServiceException.INVALID_REQUEST("header '" + name + "' not allowed", null);
}
} else {
ZimbraLog.soap.warn("unsupported child element '%s' under parent %s", elem.getName(), msgElem.getName());
}
}
// deal with things that can be either <m> attributes or subelements
String subject = msgElem.getAttribute(MailConstants.E_SUBJECT, "");
mm.setSubject(subject, CharsetUtil.checkCharset(subject, ctxt.defaultCharset));
String irt = cleanReference(msgElem.getAttribute(MailConstants.E_IN_REPLY_TO, null));
if (irt != null) {
mm.setHeader("In-Reply-To", irt);
}
// can have no addresses specified if it's a draft...
if (!maddrs.isEmpty()) {
addAddressHeaders(mm, maddrs);
}
if (!hasContent && !isMultipart) {
mm.setText("", MimeConstants.P_CHARSET_DEFAULT);
}
String flagStr = msgElem.getAttribute(MailConstants.A_FLAGS, "");
if (flagStr.indexOf(Flag.toChar(Flag.ID_HIGH_PRIORITY)) != -1) {
mm.addHeader("X-Priority", "1");
mm.addHeader("Importance", "high");
} else if (flagStr.indexOf(Flag.toChar(Flag.ID_LOW_PRIORITY)) != -1) {
mm.addHeader("X-Priority", "5");
mm.addHeader("Importance", "low");
}
// JavaMail tip: don't forget to call this, it is REALLY confusing.
mm.saveChanges();
return mm;
} catch (UnsupportedEncodingException e) {
throw ServiceException.FAILURE("UnsupportedEncodingExecption", e);
} catch (SendFailedException e) {
SafeSendFailedException ssfe = new SafeSendFailedException(e);
throw ServiceException.FAILURE("SendFailure", ssfe);
} catch (MessagingException e) {
throw ServiceException.FAILURE("MessagingExecption", e);
} catch (IOException e) {
throw ServiceException.FAILURE("IOExecption", e);
}
}
use of javax.mail.internet.MimeMultipart in project zm-mailbox by Zimbra.
the class ParseMimeMessage method setContent.
/**
* The <mp>'s from the client and the MimeBodyParts in alternatives[] all want to be "content"
* of this MimeMessage. The alternatives[] all need to be "alternative" to whatever the client sends
* us....but we want to be careful so that we do NOT create a nested multipart/alternative structure
* within another one (that would be very tacky)....so this is a bit complicated.
*/
private static void setContent(MimeMessage mm, MimeMultipart mmp, Element elem, MimeBodyPart[] alternatives, ParseMessageContext ctxt) throws MessagingException, ServiceException, IOException {
String type = elem.getAttribute(MailConstants.A_CONTENT_TYPE, MimeConstants.CT_DEFAULT).trim();
ContentType ctype = new ContentType(type, ctxt.use2231).cleanup();
// is the client passing us a multipart?
if (ctype.getPrimaryType().equals("multipart")) {
// handle multipart content separately...
setMultipartContent(ctype, mm, mmp, elem, alternatives, ctxt);
return;
}
Element inline = elem.getOptionalElement(MailConstants.E_ATTACH);
if (inline != null) {
handleAttachments(inline, mmp, ctxt, elem.getAttribute(MailConstants.A_CONTENT_ID, null), Part.INLINE);
return;
}
if (alternatives != null) {
// create a multipart/alternative to hold all the alternatives
MimeMultipart mmpNew = new ZMimeMultipart("alternative");
if (mmp == null) {
mm.setContent(mmpNew);
} else {
MimeBodyPart mbpWrapper = new ZMimeBodyPart();
mbpWrapper.setContent(mmpNew);
mmp.addBodyPart(mbpWrapper);
}
mmp = mmpNew;
}
// once we get here, mmp is either NULL, a multipart/mixed from the toplevel,
// or a multipart/alternative created just above....either way we are safe to stick
// the client's nice and simple body right here
String text = elem.getAttribute(MailConstants.E_CONTENT, "");
byte[] raw = text.getBytes(Charsets.UTF_8);
if (raw.length > 0 || !LC.mime_exclude_empty_content.booleanValue() || ctype.getPrimaryType().equals("text")) {
ctxt.incrementSize("message body", raw.length);
// if the user has specified an alternative charset, make sure it exists and can encode the content
String charset = CharsetUtil.checkCharset(text, ctxt.defaultCharset);
ctype.setCharset(charset).setParameter(MimeConstants.P_CHARSET, charset);
Object content = ctype.getContentType().equals(ContentType.MESSAGE_RFC822) ? new ZMimeMessage(JMSession.getSession(), new SharedByteArrayInputStream(raw)) : text;
if (mmp != null) {
MimeBodyPart mbp = new ZMimeBodyPart();
mbp.setContent(content, ctype.toString());
mmp.addBodyPart(mbp);
} else {
mm.setContent(content, ctype.toString());
}
}
if (alternatives != null) {
for (int i = 0; i < alternatives.length; i++) {
ctxt.incrementSize("alternative body", alternatives[i].getSize());
mmp.addBodyPart(alternatives[i]);
}
}
}
Aggregations