List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
@Override public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body) throws DispositionReportFaultMessage, RemoteException { try {/*w ww .ja v a 2 s . c om*/ log.info("Sending notification email to " + notificationEmailAddress + " from " + getEMailProperties().getProperty("mail.smtp.from", "jUDDI")); if (session != null && notificationEmailAddress != null) { MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(notificationEmailAddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(getEMailProperties().getProperty("mail.smtp.from", "jUDDI"))); //maybe nice to use a template rather then sending raw xml. String subscriptionResultXML = JAXBMarshaller.marshallToString(body, JAXBMarshaller.PACKAGE_SUBSCR_RES); Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.body"); msg_content = String .format(msg_content, StringEscapeUtils.escapeHtml(this.publisherName), StringEscapeUtils.escapeHtml(AppConfig.getConfiguration() .getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), GetSubscriptionType(body), GetChangeSummary(body)); content.setContent(msg_content, "text/html; charset=UTF-8;"); mp.addBodyPart(content); MimeBodyPart attachment = new MimeBodyPart(); attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;"); attachment.setFileName("uddiNotification.xml"); mp.addBodyPart(attachment); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " " + body.getSubscriptionResultsList().getSubscription().getSubscriptionKey()); Transport.send(message); } else { throw new DispositionReportFaultMessage("Session is null!", null); } } catch (Exception e) { log.error(e.getMessage(), e); throw new DispositionReportFaultMessage(e.getMessage(), null); } DispositionReport dr = new DispositionReport(); Result res = new Result(); dr.getResult().add(res); return dr; }
From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java
/** * Send email with Amazon Simple Email Service. * <p/>// w w w . ja va 2 s .c o m * * Please note that the sender (ie 'from') must be a verified address (see * {@link AmazonSimpleEmailService#verifyEmailAddress(com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest)} * ). * <p/> * * Please note that the sender is a CC of the meail to ease support. * <p/> * * @param subject * @param body * @param from * @param toAddresses * @throws MessagingException * @throws AddressException */ public void sendEmail(String subject, String body, AccessKey accessKey, KeyPair sshKeyPair, java.security.KeyPair x509KeyPair, X509Certificate x509Certificate, SigningCertificate signingCertificate, String from, String toAddress) { try { Session s = Session.getInstance(new Properties(), null); MimeMessage msg = new MimeMessage(s); msg.setFrom(new InternetAddress(from)); msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress)); msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(from)); msg.setSubject(subject); MimeMultipart mimeMultiPart = new MimeMultipart(); msg.setContent(mimeMultiPart); // body BodyPart plainTextBodyPart = new MimeBodyPart(); mimeMultiPart.addBodyPart(plainTextBodyPart); plainTextBodyPart.setContent(body, "text/plain"); // aws-credentials.txt / accessKey { BodyPart awsCredentialsBodyPart = new MimeBodyPart(); awsCredentialsBodyPart.setFileName("aws-credentials.txt"); StringWriter awsCredentialsStringWriter = new StringWriter(); PrintWriter awsCredentials = new PrintWriter(awsCredentialsStringWriter); awsCredentials .println("#Insert your AWS Credentials from http://aws.amazon.com/security-credentials"); awsCredentials.println("#" + new DateTime()); awsCredentials.println(); awsCredentials.println("# ec2, rds & elb tools use accessKey and secretKey"); awsCredentials.println("accessKey=" + accessKey.getAccessKeyId()); awsCredentials.println("secretKey=" + accessKey.getSecretAccessKey()); awsCredentials.println(); awsCredentials.println("# iam tools use AWSAccessKeyId and AWSSecretKey"); awsCredentials.println("AWSAccessKeyId=" + accessKey.getAccessKeyId()); awsCredentials.println("AWSSecretKey=" + accessKey.getSecretAccessKey()); awsCredentialsBodyPart.setContent(awsCredentialsStringWriter.toString(), "text/plain"); mimeMultiPart.addBodyPart(awsCredentialsBodyPart); } // private ssh key { BodyPart keyPairBodyPart = new MimeBodyPart(); keyPairBodyPart.setFileName(sshKeyPair.getKeyName() + ".pem.txt"); keyPairBodyPart.setContent(sshKeyPair.getKeyMaterial(), "application/octet-stream"); mimeMultiPart.addBodyPart(keyPairBodyPart); } // x509 private key { BodyPart x509PrivateKeyBodyPart = new MimeBodyPart(); x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem.txt"); String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate()); x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/octet-stream"); mimeMultiPart.addBodyPart(x509PrivateKeyBodyPart); } // x509 private key { BodyPart x509CertificateBodyPart = new MimeBodyPart(); x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem.txt"); String x509CertificatePem = Pems.pem(x509Certificate); x509CertificateBodyPart.setContent(x509CertificatePem, "application/octet-stream"); mimeMultiPart.addBodyPart(x509CertificateBodyPart); } // Convert to raw message ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); RawMessage rawMessage = new RawMessage(); rawMessage.setData(ByteBuffer.wrap(out.toString().getBytes())); ses.sendRawEmail(new SendRawEmailRequest().withRawMessage(rawMessage)); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java
private void processSpecificAttachment(final MimeMultipart mixedMultipart, final IContentItem attachmentContent) throws IOException, MessagingException { // Add this attachment if (attachmentContent != null) { final ByteArrayDataSource dataSource = new ByteArrayDataSource(attachmentContent.getInputStream(), attachmentContent.getMimeType()); final MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(getAttachmentName()); mixedMultipart.addBodyPart(attachmentBodyPart); }//www. j a v a2s . co m }
From source file:lucee.runtime.net.smtp.SMTPClient.java
private MimeMessageAndSession createMimeMessage(lucee.runtime.config.Config config, String hostName, int port, String username, String password, long lifeTimesan, long idleTimespan, boolean tls, boolean ssl, boolean newConnection) throws MessagingException { SessionAndTransport sat = getSessionAndTransport(config, hostName, port, username, password, lifeTimesan, idleTimespan, timeout, tls, ssl, newConnection); /*Properties props = createProperties(config,hostName,port,username,password,tls,ssl,timeout); Authenticator auth=null;//from w w w .j a va 2s . com if(!StringUtil.isEmpty(username)) auth=new SMTPAuthenticator( username, password ); SessionAndTransport sat = newConnection?new SessionAndTransport(hash(props), props, auth,lifeTimesan,idleTimespan): SMTPConnectionPool.getSessionAndTransport(props,hash(props),auth,lifeTimesan,idleTimespan); */ // Contacts SMTPMessage msg = new SMTPMessage(sat.session); if (from == null) throw new MessagingException("you have do define the from for the mail"); //if(tos==null)throw new MessagingException("you have do define the to for the mail"); checkAddress(from, charset); //checkAddress(tos,charset); msg.setFrom(from); //msg.setRecipients(Message.RecipientType.TO, tos); if (tos != null) { checkAddress(tos, charset); msg.setRecipients(Message.RecipientType.TO, tos); } if (ccs != null) { checkAddress(ccs, charset); msg.setRecipients(Message.RecipientType.CC, ccs); } if (bccs != null) { checkAddress(bccs, charset); msg.setRecipients(Message.RecipientType.BCC, bccs); } if (rts != null) { checkAddress(rts, charset); msg.setReplyTo(rts); } if (fts != null) { checkAddress(fts, charset); msg.setEnvelopeFrom(fts[0].toString()); } // Subject and headers try { msg.setSubject(MailUtil.encode(subject, charset)); } catch (UnsupportedEncodingException e) { throw new MessagingException("the encoding " + charset + " is not supported"); } msg.setHeader("X-Mailer", xmailer); msg.setHeader("Date", getNow(timeZone)); //msg.setSentDate(new Date()); Multipart mp = null; // Only HTML if (plainText == null) { if (ArrayUtil.isEmpty(attachmentz) && ArrayUtil.isEmpty(parts)) { fillHTMLText(msg); setHeaders(msg, headers); return new MimeMessageAndSession(msg, sat); } mp = new MimeMultipart("related"); mp.addBodyPart(getHTMLText()); } // only Plain else if (htmlText == null) { if (ArrayUtil.isEmpty(attachmentz) && ArrayUtil.isEmpty(parts)) { fillPlainText(msg); setHeaders(msg, headers); return new MimeMessageAndSession(msg, sat); } mp = new MimeMultipart(); mp.addBodyPart(getPlainText()); } // Plain and HTML else { mp = new MimeMultipart("alternative"); mp.addBodyPart(getPlainText()); mp.addBodyPart(getHTMLText()); if (!ArrayUtil.isEmpty(attachmentz) || !ArrayUtil.isEmpty(parts)) { MimeBodyPart content = new MimeBodyPart(); content.setContent(mp); mp = new MimeMultipart(); mp.addBodyPart(content); } } // parts if (!ArrayUtil.isEmpty(parts)) { Iterator<MailPart> it = parts.iterator(); if (mp instanceof MimeMultipart) ((MimeMultipart) mp).setSubType("alternative"); while (it.hasNext()) { mp.addBodyPart(toMimeBodyPart(it.next())); } } // Attachments if (!ArrayUtil.isEmpty(attachmentz)) { for (int i = 0; i < attachmentz.length; i++) { mp.addBodyPart(toMimeBodyPart(mp, config, attachmentz[i])); } } msg.setContent(mp); setHeaders(msg, headers); return new MimeMessageAndSession(msg, sat); }
From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * Send a Multipart text message with attached files. FIXME: use * prepareMessage method/* ww w . j a va 2 s . c o m*/ * * @param strRecipientsTo * The list of the main recipients email.Every recipient must be * separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The message. * @param fileAttachements * The list of attached files * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occured during sending * @throws MessagingException * If a messaging error occured */ protected static void sendMultipartMessageText(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, List<FileAttachment> fileAttachements, Transport transport, Session session) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session); msg.setHeader(HEADER_NAME, HEADER_VALUE); // Creation of the root part containing all the elements of the message MimeMultipart multipart = new MimeMultipart(); // Creation of the html part, the "core" of the message BodyPart msgBodyPart = new MimeBodyPart(); // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE ); msgBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_PLAIN) + AppPropertiesService.getProperty(PROPERTY_CHARSET)))); multipart.addBodyPart(msgBodyPart); // add File Attachement if (fileAttachements != null) { for (FileAttachment fileAttachement : fileAttachements) { String strFileName = fileAttachement.getFileName(); byte[] bContentFile = fileAttachement.getData(); String strContentType = fileAttachement.getType(); ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType); msgBodyPart = new MimeBodyPart(); msgBodyPart.setDataHandler(new DataHandler(dataSource)); msgBodyPart.setFileName(strFileName); msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT); multipart.addBodyPart(msgBodyPart); } } msg.setContent(multipart); sendMessage(msg, transport); }
From source file:com.szmslab.quickjavamail.send.MailSender.java
/** * ?????/*from www . java2 s .co m*/ * * @param message * * @throws MessagingException * @throws UnsupportedEncodingException */ private void setContent(MimeMessage message) throws MessagingException, UnsupportedEncodingException { if (StringUtils.isBlank(html)) { if (attachmentFileList.isEmpty()) { /* * text/plain */ message.setText(text, charset); } else { /* * multipart/mixed * text/plain * attachment */ Multipart mixedMultipart = createMixedMimeMultipart(); mixedMultipart.addBodyPart(createTextPart()); for (AttachmentFile file : attachmentFileList) { mixedMultipart.addBodyPart(createAttachmentPart(file)); } message.setContent(mixedMultipart); } } else { if (attachmentFileList.isEmpty()) { if (inlineImageFileList.isEmpty()) { /* * multipart/alternative * text/plain * text/html */ Multipart alternativeMultipart = createAlternativeMimeMultipart(); alternativeMultipart.addBodyPart(createTextPart()); alternativeMultipart.addBodyPart(createHtmlPart()); message.setContent(alternativeMultipart); } else { /* * multipart/alternative * text/plain * mulpart/related * text/html * image */ Multipart relatedMultipart = createRelatedMimeMultipart(); relatedMultipart.addBodyPart(createHtmlPart()); for (InlineImageFile file : inlineImageFileList) { relatedMultipart.addBodyPart(createImagePart(file)); } MimeBodyPart relatedPart = new MimeBodyPart(); relatedPart.setContent(relatedMultipart); Multipart alternativeMultipart = createAlternativeMimeMultipart(); alternativeMultipart.addBodyPart(createTextPart()); alternativeMultipart.addBodyPart(relatedPart); message.setContent(alternativeMultipart); } } else { if (inlineImageFileList.isEmpty()) { /* * multipart/mixed * mulpart/alternative * text/plain * text/html * attachment */ Multipart alternativeMultipart = createAlternativeMimeMultipart(); alternativeMultipart.addBodyPart(createTextPart()); alternativeMultipart.addBodyPart(createHtmlPart()); MimeBodyPart alternativePart = new MimeBodyPart(); alternativePart.setContent(alternativeMultipart); Multipart mixedMultipart = createMixedMimeMultipart(); mixedMultipart.addBodyPart(alternativePart); for (AttachmentFile file : attachmentFileList) { mixedMultipart.addBodyPart(createAttachmentPart(file)); } message.setContent(mixedMultipart); } else { /* * multipart/mixed * mulpart/alternative * text/plain * mulpart/related * text/html * image * attachment */ Multipart relatedMultipart = createRelatedMimeMultipart(); relatedMultipart.addBodyPart(createHtmlPart()); for (InlineImageFile file : inlineImageFileList) { relatedMultipart.addBodyPart(createImagePart(file)); } MimeBodyPart relatedPart = new MimeBodyPart(); relatedPart.setContent(relatedMultipart); Multipart alternativeMultipart = createAlternativeMimeMultipart(); alternativeMultipart.addBodyPart(createTextPart()); alternativeMultipart.addBodyPart(relatedPart); MimeBodyPart alternativePart = new MimeBodyPart(); alternativePart.setContent(alternativeMultipart); Multipart mixedMultipart = createMixedMimeMultipart(); mixedMultipart.addBodyPart(alternativePart); for (AttachmentFile file : attachmentFileList) { mixedMultipart.addBodyPart(createAttachmentPart(file)); } message.setContent(mixedMultipart); } } } setHeaderToPart(message); }
From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java
/**Builds up a new message from the passed message parts * @param messageType one of the message types definfed in the class AS2Message *//* w w w. j a v a 2 s. c o m*/ public AS2Message createMessage(Partner sender, Partner receiver, AS2Payload[] payloads, int messageType, String messageId) throws Exception { if (messageId == null) { messageId = UniqueId.createMessageId(sender.getAS2Identification(), receiver.getAS2Identification()); } BCCryptoHelper cryptoHelper = new BCCryptoHelper(); AS2MessageInfo info = new AS2MessageInfo(); info.setMessageType(messageType); info.setSenderId(sender.getAS2Identification()); info.setReceiverId(receiver.getAS2Identification()); info.setSenderEMail(sender.getEmail()); info.setMessageId(messageId); info.setDirection(AS2MessageInfo.DIRECTION_OUT); info.setSignType(receiver.getSignType()); info.setEncryptionType(receiver.getEncryptionType()); info.setRequestsSyncMDN(receiver.isSyncMDN()); if (!receiver.isSyncMDN()) { info.setAsyncMDNURL(sender.getMdnURL()); } info.setSubject(receiver.getSubject()); try { info.setSenderHost(InetAddress.getLocalHost().getCanonicalHostName()); } catch (UnknownHostException e) { //nop } //create message object to return AS2Message message = new AS2Message(info); //stores all the available body parts that have been prepared List<MimeBodyPart> contentPartList = new ArrayList<MimeBodyPart>(); for (AS2Payload as2Payload : payloads) { //add payload message.addPayload(as2Payload); if (this.runtimeConnection != null) { MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection); messageAccess.initializeOrUpdateMessage(info); } //no MIME message: single payload, unsigned, no CEM if (info.getSignType() == AS2Message.SIGNATURE_NONE && payloads.length == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) { return (this.createMessageNoMIME(message, receiver)); } //MIME message MimeBodyPart bodyPart = new MimeBodyPart(); String contentType = null; if (as2Payload.getContentType() == null) { contentType = receiver.getContentType(); } else { contentType = as2Payload.getContentType(); } bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(as2Payload.getData(), contentType))); bodyPart.addHeader("Content-Type", contentType); if (as2Payload.getContentId() != null) { bodyPart.addHeader("Content-ID", as2Payload.getContentId()); } if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) { bodyPart.addHeader("Content-Transfer-Encoding", "base64"); } else { bodyPart.addHeader("Content-Transfer-Encoding", "binary"); } //prepare filename to not violate the MIME header rules if (as2Payload.getOriginalFilename() == null) { as2Payload.setOriginalFilename(new File(as2Payload.getPayloadFilename()).getName()); } String newFilename = as2Payload.getOriginalFilename().replace(' ', '_'); newFilename = newFilename.replace('@', '_'); newFilename = newFilename.replace(':', '_'); newFilename = newFilename.replace(';', '_'); newFilename = newFilename.replace('(', '_'); newFilename = newFilename.replace(')', '_'); bodyPart.addHeader("Content-Disposition", "attachment; filename=" + newFilename); contentPartList.add(bodyPart); } Part contentPart = null; //sigle attachment? No CEM? Every CEM is in a multipart/related container if (contentPartList.size() == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) { contentPart = contentPartList.get(0); } else { //build up a new MimeMultipart container for the multiple attachments, content-type //is "multipart/related" MimeMultipart multipart = null; //CEM messages are always in a multipart container (even the response which contains only a single //payload) with the subtype "application/ediint-cert-exchange+xml". if (info.getMessageType() == AS2Message.MESSAGETYPE_CEM) { multipart = new MimeMultipart("related; type=\"application/ediint-cert-exchange+xml\""); } else { multipart = new MimeMultipart("related"); } for (MimeBodyPart bodyPart : contentPartList) { multipart.addBodyPart(bodyPart); } contentPart = new MimeMessage(Session.getInstance(System.getProperties(), null)); contentPart.setContent(multipart, multipart.getContentType()); ((MimeMessage) contentPart).saveChanges(); } //should the content be compressed and enwrapped or just enwrapped? if (receiver.getCompressionType() == AS2Message.COMPRESSION_ZLIB) { info.setCompressionType(AS2Message.COMPRESSION_ZLIB); int uncompressedSize = contentPart.getSize(); contentPart = this.compressPayload(receiver, contentPart); int compressedSize = contentPart.getSize(); //sometimes size() is unable to determine the size of the compressed body part and will return -1. Dont log the //compression ratio in this case. if (uncompressedSize == -1 || compressedSize == -1) { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed.unknownratio", new Object[] { info.getMessageId() }), info); } } else { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed", new Object[] { info.getMessageId(), AS2Tools.getDataSizeDisplay(uncompressedSize), AS2Tools.getDataSizeDisplay(compressedSize) }), info); } } } //compute content mic. Try to use sign digest as hash alg. For unsigned messages take sha-1 String digestOID = null; if (info.getSignType() == AS2Message.SIGNATURE_MD5) { digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_MD5); } else { digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1); } String mic = cryptoHelper.calculateMIC(contentPart, digestOID); if (info.getSignType() == AS2Message.SIGNATURE_MD5) { info.setReceivedContentMIC(mic + ", md5"); } else { info.setReceivedContentMIC(mic + ", sha1"); } this.enwrappInMessageAndSign(message, contentPart, sender, receiver); //encryption requested for the receiver? if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) { String cryptAlias = this.encryptionCertManager .getAliasByFingerprint(receiver.getCryptFingerprintSHA1()); this.encryptDataToMessage(message, cryptAlias, info.getEncryptionType(), receiver); } else { message.setRawData(message.getDecryptedRawData()); if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("message.notencrypted", new Object[] { info.getMessageId() }), info); } } return (message); }
From source file:org.apache.synapse.transport.mail.MailTransportSender.java
/** * Populate email with a SOAP formatted message * @param outInfo the out transport information holder * @param msgContext the message context that holds the message to be written * @throws AxisFault on error// w w w .j a v a 2 s . c o m */ private void sendMail(MailOutTransportInfo outInfo, MessageContext msgContext) throws AxisFault, MessagingException, IOException { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = null; try { messageFormatter = TransportUtils.getMessageFormatter(msgContext); } catch (AxisFault axisFault) { throw new BaseTransportException("Unable to get the message formatter to use"); } WSMimeMessage message = new WSMimeMessage(session); Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); // set From address - first check if this is a reply, then use from address from the // transport out, else if any custom transport headers set on this message, or default // to the transport senders default From address if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) { message.setFrom(outInfo.getFromAddress()); message.setReplyTo((new Address[] { outInfo.getFromAddress() })); } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) { message.setFrom(new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); message.setReplyTo(InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); } else { if (smtpFromAddress != null) { message.setFrom(smtpFromAddress); message.setReplyTo(new Address[] { smtpFromAddress }); } else { handleException("From address for outgoing message cannot be determined"); } } // set To address/es to any custom transport header set on the message, else use the reply // address from the out transport information if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO))); } else if (outInfo.getTargetAddresses() != null) { message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses()); } else { handleException("To address for outgoing message cannot be determined"); } // set Cc address/es to any custom transport header set on the message, else use the // Cc list from original request message if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC))); } else if (outInfo.getTargetAddresses() != null) { message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses()); } // set Bcc address/es to any custom addresses set at the transport sender level + any // custom transport header InternetAddress[] trpBccArr = null; if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) { trpBccArr = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC)); } InternetAddress[] mergedBcc = new InternetAddress[(trpBccArr != null ? trpBccArr.length : 0) + (smtpBccAddresses != null ? smtpBccAddresses.length : 0)]; if (trpBccArr != null) { System.arraycopy(trpBccArr, 0, mergedBcc, 0, trpBccArr.length); } if (smtpBccAddresses != null) { System.arraycopy(smtpBccAddresses, 0, mergedBcc, mergedBcc.length, smtpBccAddresses.length); } if (mergedBcc != null) { message.setRecipients(Message.RecipientType.BCC, mergedBcc); } // set subject if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) { message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)); } else if (outInfo.getSubject() != null) { message.setSubject(outInfo.getSubject()); } else { message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction()); } // if a custom message id is set, use it if (msgContext.getMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID()); message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID()); } // if this is a reply, set reference to original message if (outInfo.getRequestMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID()); message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID()); } else { if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO)); } if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) { message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES)); } } // set Date message.setSentDate(new Date()); // set SOAPAction header message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); // write body ByteArrayOutputStream baos = null; String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()); DataHandler dataHandler = null; MimeMultipart mimeMultiPart = null; OMElement firstChild = msgContext.getEnvelope().getBody().getFirstElement(); if (firstChild != null) { if (BaseConstants.DEFAULT_BINARY_WRAPPER.equals(firstChild.getQName())) { baos = new ByteArrayOutputStream(); OMNode omNode = firstChild.getFirstOMChild(); if (omNode != null && omNode instanceof OMText) { Object dh = ((OMText) omNode).getDataHandler(); if (dh != null && dh instanceof DataHandler) { dataHandler = (DataHandler) dh; } } } else if (BaseConstants.DEFAULT_TEXT_WRAPPER.equals(firstChild.getQName())) { if (firstChild instanceof OMSourcedElementImpl) { baos = new ByteArrayOutputStream(); try { firstChild.serializeAndConsume(baos); } catch (XMLStreamException e) { handleException("Error serializing 'text' payload from OMSourcedElement", e); } dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()), MailConstants.TEXT_PLAIN); } else { dataHandler = new DataHandler(firstChild.getText(), MailConstants.TEXT_PLAIN); } } else { baos = new ByteArrayOutputStream(); messageFormatter.writeTo(msgContext, format, baos, true); // create the data handler dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()), contentType); String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT); if (mFormat == null) { mFormat = defaultMailFormat; } if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) { mimeMultiPart = new MimeMultipart(); MimeBodyPart mimeBodyPart1 = new MimeBodyPart(); mimeBodyPart1.setContent("Web Service Message Attached", "text/plain"); MimeBodyPart mimeBodyPart2 = new MimeBodyPart(); mimeBodyPart2.setDataHandler(dataHandler); mimeBodyPart2.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); } else { message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); } } } try { if (mimeMultiPart == null) { message.setDataHandler(dataHandler); } else { message.setContent(mimeMultiPart); } Transport.send(message); } catch (MessagingException e) { handleException("Error creating mail message or sending it to the configured server", e); } finally { try { if (baos != null) { baos.close(); } } catch (IOException ignore) { } } }
From source file:fsi_admin.JSmtpConn.java
@SuppressWarnings("rawtypes") private boolean adjuntarArchivo(StringBuffer msj, BodyPart messagebodypart, MimeMultipart multipart, Vector archivos) {//from w ww .j a v a2 s.c o m if (!archivos.isEmpty()) { FileItem actual = null; try { for (int i = 0; i < archivos.size(); i++) { InputStream inputStream = null; try { actual = (FileItem) archivos.elementAt(i); inputStream = actual.getInputStream(); byte[] sourceBytes = IOUtils.toByteArray(inputStream); String name = actual.getName(); messagebodypart = new MimeBodyPart(); ByteArrayDataSource rawData = new ByteArrayDataSource(sourceBytes); DataHandler data = new DataHandler(rawData); messagebodypart.setDataHandler(data); messagebodypart.setFileName(name); multipart.addBodyPart(messagebodypart); //////////////////////////////////////////////// /* messagebodypart = new MimeBodyPart(); DataSource source = new FileDataSource(new File(actual.getName())); byte[] sourceBytes = actual.get(); OutputStream sourceOS = source.getOutputStream(); sourceOS.write(sourceBytes); messagebodypart.setDataHandler(new DataHandler(source)); messagebodypart.setFileName(actual.getName()); multipart.addBodyPart(messagebodypart); */ /////////////////////////////////////////////////////// } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return true; } catch (MessagingException e) { e.printStackTrace(); msj.append("Error de Mensajeria al cargar adjunto SMTP: " + e.getMessage()); return false; } catch (IOException e) { e.printStackTrace(); msj.append("Error de Entrada/Salida al cargar adjunto SMTP: " + e.getMessage()); return false; } } else return true; }
From source file:org.apache.james.transport.mailets.DSNBounce.java
private MimeBodyPart createAttachedOriginal(Mail originalMail, TypeCode attachmentType) throws MessagingException { MimeBodyPart part = new MimeBodyPart(); MimeMessage originalMessage = originalMail.getMessage(); if (attachmentType.equals(TypeCode.HEADS)) { part.setContent(new MimeMessageUtils(originalMessage).getMessageHeaders(), "text/plain"); part.setHeader("Content-Type", "text/rfc822-headers"); } else {//from w ww . ja v a2 s . c o m part.setContent(originalMessage, "message/rfc822"); } if ((originalMessage.getSubject() != null) && (originalMessage.getSubject().trim().length() > 0)) { part.setFileName(originalMessage.getSubject().trim()); } else { part.setFileName("No Subject"); } part.setDisposition("Attachment"); return part; }