use of javax.activation.DataHandler in project zm-mailbox by Zimbra.
the class UUEncodeConverter method visitMessage.
@Override
protected boolean visitMessage(MimeMessage mm, VisitPhase visitKind) throws MessagingException {
// do the decode in the exit phase
if (visitKind != VisitPhase.VISIT_END)
return false;
MimeMultipart mmp = null;
try {
// only check "text/plain" parts for uudecodeable attachments
if (!mm.isMimeType(MimeConstants.CT_TEXT_PLAIN))
return false;
// don't check transfer-encoded parts for uudecodeable attachments
String cte = mm.getHeader("Content-Transfer-Encoding", null);
if (cte != null) {
cte = cte.trim().toLowerCase();
if (!cte.equals(MimeConstants.ET_7BIT) && !cte.equals(MimeConstants.ET_8BIT) && !cte.equals(MimeConstants.ET_BINARY))
return false;
}
List<UUDecodedFile> uufiles = null;
// go through top-level text/plain part and extract uuencoded files
PositionInputStream is = null;
long size;
try {
is = new PositionInputStream(new BufferedInputStream(mm.getInputStream()));
for (int c = is.read(); c != -1; ) {
long start = is.getPosition() - 1;
// check for uuencode header: "begin NNN filename"
if (c == 'b' && (c = is.read()) == 'e' && (c = is.read()) == 'g' && (c = is.read()) == 'i' && (c = is.read()) == 'n' && ((c = is.read()) == ' ' || c == '\t') && Character.isDigit((c = is.read())) && Character.isDigit(c = is.read()) && Character.isDigit(c = is.read()) && ((c = is.read()) == ' ' || c == '\t')) {
StringBuilder sb = new StringBuilder();
while ((c = is.read()) != '\r' && c != '\n' && c != -1) sb.append((char) c);
String filename = FileUtil.trimFilename(sb.toString().trim());
if (c != -1 && filename.length() > 0) {
if (uufiles == null)
uufiles = new ArrayList<UUDecodedFile>(3);
try {
uufiles.add(new UUDecodedFile(is, filename, start));
// check to make sure that the caller's OK with altering the message
if (uufiles.size() == 1 && mCallback != null && !mCallback.onModification())
return false;
} catch (IOException ioe) {
}
}
}
// skip to the beginning of the next line
while (c != '\r' && c != '\n' && c != -1) c = is.read();
while (c == '\r' || c == '\n') c = is.read();
}
size = is.getPosition();
} finally {
ByteUtil.closeStream(is);
}
if (uufiles == null || uufiles.isEmpty())
return false;
// create MimeParts for the extracted files
mmp = new ZMimeMultipart("mixed");
for (UUDecodedFile uu : uufiles) {
MimeBodyPart mbp = new ZMimeBodyPart();
mbp.setHeader("Content-Type", uu.getContentType());
mbp.setHeader("Content-Disposition", new ContentDisposition(Part.ATTACHMENT).setParameter("filename", uu.getFilename()).toString());
mbp.setDataHandler(new DataHandler(uu.getDataSource()));
mmp.addBodyPart(mbp);
size -= uu.getEndOffset() - uu.getStartOffset();
}
// take the remaining text and put it in as the first "related" part
InputStream isOrig = null;
try {
isOrig = mm.getInputStream();
long offset = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream((int) size);
byte[] buffer = new byte[8192];
for (UUDecodedFile uu : uufiles) {
long count = uu.getStartOffset() - offset, numRead;
while (count > 0 && (numRead = isOrig.read(buffer, 0, (int) Math.min(count, 8192))) >= 0) {
baos.write(buffer, 0, (int) numRead);
count -= numRead;
}
isOrig.skip(uu.getEndOffset() - uu.getStartOffset());
offset = uu.getEndOffset();
}
ByteUtil.copy(isOrig, true, baos, true);
MimeBodyPart mbp = new ZMimeBodyPart();
mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(baos.toByteArray(), MimeConstants.CT_TEXT_PLAIN)));
mmp.addBodyPart(mbp, 0);
} finally {
ByteUtil.closeStream(isOrig);
}
} catch (MessagingException e) {
ZimbraLog.extensions.warn("exception while uudecoding message part; skipping part", e);
return false;
} catch (IOException e) {
ZimbraLog.extensions.warn("exception while uudecoding message part; skipping part", e);
return false;
}
// replace the top-level part with a new multipart/related
mm.setContent(mmp);
mm.setHeader("Content-Type", mmp.getContentType() + "; generated=true");
return true;
}
use of javax.activation.DataHandler in project zm-mailbox by Zimbra.
the class ParseMimeMessage method attachDocument.
private static void attachDocument(MimeMultipart mmp, Document doc, String contentID, ParseMessageContext ctxt) throws MessagingException, ServiceException {
ctxt.incrementSize("attached document", (long) (doc.getSize() * 1.33));
ContentType ct = new ContentType(doc.getContentType());
if (MimeConstants.isZimbraDocument(ct.getContentType())) {
ct = new ContentType(MimeConstants.CT_TEXT_HTML);
}
MimeBodyPart mbp = new ZMimeBodyPart();
mbp.setDataHandler(new DataHandler(new MailboxBlobDataSource(doc.getBlob(), ct.getContentType())));
mbp.setHeader("Content-Type", ct.cleanup().setParameter("name", doc.getName()).setCharset(ctxt.defaultCharset).toString());
mbp.setHeader("Content-Disposition", new ContentDisposition(Part.ATTACHMENT).setParameter("filename", doc.getName()).toString());
mbp.setContentID(contentID);
mmp.addBodyPart(mbp);
}
use of javax.activation.DataHandler in project zm-mailbox by Zimbra.
the class CalendarMailSender method createCalendarMessage.
public static MimeMessage createCalendarMessage(Account account, Address fromAddr, Address senderAddr, List<Address> toAddrs, String subject, String desc, String descHtml, String uid, ZCalendar.ZVCalendar cal, List<Attach> attaches, boolean replyToSender) throws ServiceException {
if (desc == null)
desc = "";
try {
MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSmtpSession(account));
MimeMultipart mpAlternatives = new ZMimeMultipart("alternative");
if (attaches != null && !attaches.isEmpty()) {
MimeMultipart mpMixed = new ZMimeMultipart("mixed");
mm.setContent(mpMixed);
MimeBodyPart mbpWrapper = new ZMimeBodyPart();
mbpWrapper.setContent(mpAlternatives);
mpMixed.addBodyPart(mbpWrapper);
for (Attach attach : attaches) {
byte[] rawData = attach.getDecodedData();
if (rawData == null) {
continue;
}
ContentDisposition cdisp = new ContentDisposition(Part.ATTACHMENT, true);
String ctypeAsString = attach.getContentType();
if (ctypeAsString == null) {
ctypeAsString = MimeConstants.CT_APPLICATION_OCTET_STREAM;
}
ContentType ctype = new ContentType(ctypeAsString);
if (attach.getFileName() != null) {
ctype.setParameter("name", attach.getFileName());
cdisp.setParameter("filename", attach.getFileName());
}
MimeBodyPart mbp2 = new ZMimeBodyPart();
ByteArrayDataSource bads = new ByteArrayDataSource(rawData, ctypeAsString);
mbp2.setDataHandler(new DataHandler(bads));
mbp2.setHeader("Content-Type", ctype.toString());
mbp2.setHeader("Content-Disposition", cdisp.toString());
mbp2.setHeader("Content-Transfer-Encoding", "base64");
mpMixed.addBodyPart(mbp2);
}
} else {
mm.setContent(mpAlternatives);
}
// Add the text as DESCRIPTION property in the iCalendar part.
// MS Entourage for Mac wants this. It ignores text/plain and
// text/html MIME parts.
cal.addDescription(desc, null);
// ///////
// TEXT part (add me first!)
MimeBodyPart textPart = new ZMimeBodyPart();
textPart.setText(desc, MimeConstants.P_CHARSET_UTF8);
mpAlternatives.addBodyPart(textPart);
// HTML part is needed to keep Outlook happy as it doesn't know
// how to deal with a message with only text/plain but no HTML.
MimeBodyPart htmlPart = new ZMimeBodyPart();
if (descHtml != null) {
ContentType ct = new ContentType(MimeConstants.CT_TEXT_HTML);
ct.setParameter(MimeConstants.P_CHARSET, MimeConstants.P_CHARSET_UTF8);
htmlPart.setText(descHtml, MimeConstants.P_CHARSET_UTF8);
htmlPart.setHeader("Content-Type", ct.toString());
} else {
htmlPart.setDataHandler(new DataHandler(new HtmlPartDataSource(desc)));
}
mpAlternatives.addBodyPart(htmlPart);
// ///////
// CALENDAR part
MimeBodyPart icalPart = makeICalIntoMimePart(cal);
mpAlternatives.addBodyPart(icalPart);
// MESSAGE HEADERS
if (subject != null) {
mm.setSubject(subject, MimeConstants.P_CHARSET_UTF8);
}
if (toAddrs != null) {
Address[] addrs = new Address[toAddrs.size()];
toAddrs.toArray(addrs);
mm.addRecipients(javax.mail.Message.RecipientType.TO, addrs);
}
if (fromAddr != null)
mm.setFrom(fromAddr);
if (senderAddr != null) {
mm.setSender(senderAddr);
if (replyToSender) {
mm.setReplyTo(new Address[] { senderAddr });
}
}
mm.setSentDate(new Date());
mm.saveChanges();
return mm;
} catch (MessagingException e) {
throw ServiceException.FAILURE("Messaging Exception while building MimeMessage from invite", e);
}
}
use of javax.activation.DataHandler in project zm-mailbox by Zimbra.
the class CreateContact method parseAttachment.
private static Attachment parseAttachment(Element elt, String name, ZimbraSoapContext zsc, OperationContext octxt, Contact existing) throws ServiceException {
// check for uploaded attachment
String attachId = elt.getAttribute(MailConstants.A_ATTACHMENT_ID, null);
if (attachId != null) {
if (Contact.isSMIMECertField(name)) {
elt.setText(parseCertificate(elt, name, zsc, octxt, existing));
return null;
} else {
Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), attachId, zsc.getAuthToken());
UploadDataSource uds = new UploadDataSource(up);
return new Attachment(new DataHandler(uds), name, (int) up.getSize());
}
}
int itemId = (int) elt.getAttributeLong(MailConstants.A_ID, -1);
String part = elt.getAttribute(MailConstants.A_PART, null);
if (itemId != -1 || (part != null && existing != null)) {
MailItem item = itemId == -1 ? existing : getRequestedMailbox(zsc).getItemById(octxt, itemId, MailItem.Type.UNKNOWN);
try {
if (item instanceof Contact) {
Contact contact = (Contact) item;
if (part != null && !part.equals("")) {
try {
int partNum = Integer.parseInt(part) - 1;
if (partNum >= 0 && partNum < contact.getAttachments().size()) {
Attachment att = contact.getAttachments().get(partNum);
return new Attachment(att.getDataHandler(), name, att.getSize());
}
} catch (NumberFormatException nfe) {
}
throw ServiceException.INVALID_REQUEST("invalid contact part number: " + part, null);
} else {
VCard vcf = VCard.formatContact(contact);
return new Attachment(vcf.getFormatted().getBytes("utf-8"), "text/x-vcard; charset=utf-8", name, vcf.fn + ".vcf");
}
} else if (item instanceof Message) {
Message msg = (Message) item;
if (part != null && !part.equals("")) {
try {
MimePart mp = Mime.getMimePart(msg.getMimeMessage(), part);
if (mp == null) {
throw MailServiceException.NO_SUCH_PART(part);
}
DataSource ds = new MimePartDataSource(mp);
return new Attachment(new DataHandler(ds), name);
} catch (MessagingException me) {
throw ServiceException.FAILURE("error parsing blob", me);
}
} else {
DataSource ds = new MessageDataSource(msg);
return new Attachment(new DataHandler(ds), name, (int) msg.getSize());
}
} else if (item instanceof Document) {
Document doc = (Document) item;
if (part != null && !part.equals("")) {
throw MailServiceException.NO_SUCH_PART(part);
}
DataSource ds = new DocumentDataSource(doc);
return new Attachment(new DataHandler(ds), name, (int) doc.getSize());
}
} catch (IOException ioe) {
throw ServiceException.FAILURE("error attaching existing item data", ioe);
} catch (MessagingException e) {
throw ServiceException.FAILURE("error attaching existing item data", e);
}
}
return null;
}
use of javax.activation.DataHandler in project jmeter by apache.
the class SendMailCommand method prepareMessage.
/**
* Prepares message prior to be sent via execute()-method, i.e. sets
* properties such as protocol, authentication, etc.
*
* @return Message-object to be sent to execute()-method
* @throws MessagingException
* when problems constructing or sending the mail occur
* @throws IOException
* when the mail content can not be read or truststore problems
* are detected
*/
public Message prepareMessage() throws MessagingException, IOException {
Properties props = new Properties();
String protocol = getProtocol();
// set properties using JAF
props.setProperty("mail." + protocol + ".host", smtpServer);
props.setProperty("mail." + protocol + ".port", getPort());
props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication));
// set timeout
props.setProperty("mail." + protocol + ".timeout", getTimeout());
props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout());
if (useStartTLS || useSSL) {
try {
String allProtocols = StringUtils.join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " ");
logger.info("Use ssl/tls protocols for mail: " + allProtocols);
props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols);
} catch (Exception e) {
logger.error("Problem setting ssl/tls protocols for mail", e);
}
}
if (enableDebug) {
props.setProperty("mail.debug", "true");
}
if (useStartTLS) {
props.setProperty("mail.smtp.starttls.enable", "true");
if (enforceStartTLS) {
// Requires JavaMail 1.4.2+
props.setProperty("mail.smtp.starttls.require", "true");
}
}
if (trustAllCerts) {
if (useSSL) {
props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false");
} else if (useStartTLS) {
props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");
}
} else if (useLocalTrustStore) {
File truststore = new File(trustStoreToUse);
logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
if (!truststore.exists()) {
logger.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse);
logger.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath());
if (!truststore.exists()) {
logger.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution.");
throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath());
}
}
if (useSSL) {
// Requires JavaMail 1.4.2+
props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
props.put("mail.smtps.ssl.socketFactory.fallback", "false");
} else if (useStartTLS) {
// Requires JavaMail 1.4.2+
props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
props.put("mail.smtp.ssl.socketFactory.fallback", "false");
}
}
session = Session.getInstance(props, null);
Message message;
if (sendEmlMessage) {
message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
} else {
message = new MimeMessage(session);
// handle body and attachments
Multipart multipart = new MimeMultipart();
final int attachmentCount = attachments.size();
if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
if (attachmentCount == 1) {
// i.e. mailBody is empty
File first = attachments.get(0);
try (FileInputStream fis = new FileInputStream(first);
InputStream is = new BufferedInputStream(fis)) {
message.setText(IOUtils.toString(is, Charset.defaultCharset()));
}
} else {
message.setText(mailBody);
}
} else {
BodyPart body = new MimeBodyPart();
body.setText(mailBody);
multipart.addBodyPart(body);
for (File f : attachments) {
BodyPart attach = new MimeBodyPart();
attach.setFileName(f.getName());
attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
multipart.addBodyPart(attach);
}
message.setContent(multipart);
}
}
// set from field and subject
if (null != sender) {
message.setFrom(new InternetAddress(sender));
}
if (null != replyTo) {
InternetAddress[] to = new InternetAddress[replyTo.size()];
message.setReplyTo(replyTo.toArray(to));
}
if (null != subject) {
message.setSubject(subject);
}
if (receiverTo != null) {
InternetAddress[] to = new InternetAddress[receiverTo.size()];
receiverTo.toArray(to);
message.setRecipients(Message.RecipientType.TO, to);
}
if (receiverCC != null) {
InternetAddress[] cc = new InternetAddress[receiverCC.size()];
receiverCC.toArray(cc);
message.setRecipients(Message.RecipientType.CC, cc);
}
if (receiverBCC != null) {
InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
receiverBCC.toArray(bcc);
message.setRecipients(Message.RecipientType.BCC, bcc);
}
for (int i = 0; i < headerFields.size(); i++) {
Argument argument = (Argument) headerFields.get(i).getObjectValue();
message.setHeader(argument.getName(), argument.getValue());
}
message.saveChanges();
return message;
}
Aggregations