List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:org.sakaiproject.tool.mailtool.Mailtool.java
public String processSendEmail() { /* EmailUser */ selected = m_recipientSelector.getSelectedUsers(); if (m_selectByTree) { selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers(); selectedGroupUsers = m_recipientSelector2.getSelectedUsers(); selectedSectionUsers = m_recipientSelector3.getSelectedUsers(); selected.addAll(selectedGroupAwareRoleUsers); selected.addAll(selectedGroupUsers); selected.addAll(selectedSectionUsers); }/*from w ww.j av a 2 s . c om*/ // Put everyone in a set so the same person doesn't get multiple emails. Set emailusers = new TreeSet(); if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future for (Iterator i = getEmailGroups().iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); emailusers.addAll(group.getEmailusers()); } } if (isAllGroupSelected()) { for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("section")) { selected.addAll(group.getEmailusers()); } } } if (isAllSectionSelected()) { for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("group")) { selected.addAll(group.getEmailusers()); } } } if (isAllGroupAwareRoleSelected()) { for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("role_groupaware")) { selected.addAll(group.getEmailusers()); } } } emailusers = new TreeSet(selected); // convert List to Set (remove duplicates) m_subjectprefix = getSubjectPrefixFromConfig(); EmailUser curUser = getCurrentUser(); String fromEmail = ""; String fromDisplay = ""; if (curUser != null) { fromEmail = curUser.getEmail(); fromDisplay = curUser.getDisplayname(); } String fromString = fromDisplay + " <" + fromEmail + ">"; m_results = "Message sent to: <br>"; String subject = m_subject; //Should we append this to the archive? String emailarchive = "/mailarchive/channel/" + m_siteid + "/main"; if (m_archiveMessage && isEmailArchiveInSite()) { String attachment_info = "<br/>"; Attachment a = null; Iterator iter = attachedFiles.iterator(); int i = 0; while (iter.hasNext()) { a = (Attachment) iter.next(); attachment_info += "<br/>"; attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize() + " Bytes)"; i++; } this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info); } List headers = new ArrayList(); if (getTextFormat().equals("htmltext")) headers.add("content-type: text/html"); else headers.add("content-type: text/plain"); String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); //String smtp_port = ServerConfigurationService.getString("smtp.port"); try { Properties props = new Properties(); props.put("mail.smtp.host", smtp_server); //props.put("mail.smtp.port", smtp_port); Session s = Session.getInstance(props, null); MimeMessage message = new MimeMessage(s); InternetAddress from = new InternetAddress(fromString); message.setFrom(from); String reply = getReplyToSelected().trim().toLowerCase(); if (reply.equals("yes")) { // "reply to sender" is default. So do nothing } else if (reply.equals("no")) { String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">"; InternetAddress noreplyemail = new InternetAddress(noreply); message.setFrom(noreplyemail); } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) { // need input(email) validation InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) }; message.setReplyTo(replytoList); } message.setSubject(subject); String text = m_body; String attachmentdirectory = getUploadDirectory(); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message String messagetype = ""; if (getTextFormat().equals("htmltext")) { messagetype = "text/html"; } else { messagetype = "text/plain"; } messageBodyPart.setContent(text, messagetype); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment Attachment a = null; Iterator iter = attachedFiles.iterator(); while (iter.hasNext()) { a = (Attachment) iter.next(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource( attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename()); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(a.getFilename()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); //Send the emails String recipientsString = ""; for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") { EmailUser euser = (EmailUser) i.next(); String toEmail = euser.getEmail(); // u.getEmail(); String toDisplay = euser.getDisplayname(); // u.getDisplayName(); // if AllUsers are selected, do not add current user's email to recipients if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) { // don't add sender to recipients } else { recipientsString += toEmail; m_results += toDisplay + (i.hasNext() ? "<br/>" : ""); } // InternetAddress to[] = {new InternetAddress(toEmail) }; // Transport.send(message,to); } if (m_otheremails.trim().equals("") != true) { // // multiple email validation is needed here // String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ','); recipientsString += refinedOtherEmailAddresses; m_results += "<br/>" + refinedOtherEmailAddresses; // InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) }; // Transport.send(message, to); } if (m_sendmecopy) { message.addRecipients(Message.RecipientType.CC, fromEmail); // trying to solve SAK-7410 // recipientsString+=fromEmail; // InternetAddress to[] = {new InternetAddress(fromEmail) }; // Transport.send(message, to); } // message.addRecipients(Message.RecipientType.TO, recipientsString); message.addRecipients(Message.RecipientType.BCC, recipientsString); Transport.send(message); } catch (Exception e) { log.debug("Mailtool Exception while trying to send the email: " + e.getMessage()); } // Clear the Subject and Body of the Message m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix(); m_otheremails = ""; m_body = ""; num_files = 0; attachedFiles.clear(); m_recipientSelector = null; m_recipientSelector1 = null; m_recipientSelector2 = null; m_recipientSelector3 = null; setAllUsersSelected(false); setAllGroupSelected(false); setAllSectionSelected(false); // Display Users with Bad Emails if the option is turned on. boolean showBadEmails = getDisplayInvalidEmailAddr(); if (showBadEmails == true) { m_results += "<br/><br/>"; List /* String */ badnames = new ArrayList(); for (Iterator i = selected.iterator(); i.hasNext();) { EmailUser user = (EmailUser) i.next(); /* This check should maybe be some sort of regular expression */ if (user.getEmail().equals("")) { badnames.add(user.getDisplayname()); } } if (badnames.size() > 0) { m_results += "The following users do not have valid email addresses:<br/>"; for (Iterator i = badnames.iterator(); i.hasNext();) { String name = (String) i.next(); if (i.hasNext() == true) m_results += name + "/ "; else m_results += name; } } } return "results"; }
From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java
@Override public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body, List<NodeRef> attachments, boolean html) throws Exception { EmailConfig config = getConfig();/*from ww w . ja v a 2 s . c o m*/ EmailProvider provider = getEmailProvider(config.getProviderId()); Properties props = System.getProperties(); String prefix = "mail." + provider.getOutgoingProto() + "."; props.put(prefix + "host", provider.getOutgoingServer()); props.put(prefix + "port", provider.getOutgoingPort()); props.put(prefix + "auth", "true"); Session session = Session.getInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName())); if (to != null) { InternetAddress[] recipients = new InternetAddress[to.size()]; for (int i = 0; i < to.size(); i++) recipients[i] = new InternetAddress(to.get(i)); msg.setRecipients(Message.RecipientType.TO, recipients); } if (cc != null) { InternetAddress[] recipients = new InternetAddress[cc.size()]; for (int i = 0; i < cc.size(); i++) recipients[i] = new InternetAddress(cc.get(i)); msg.setRecipients(Message.RecipientType.CC, recipients); } if (bcc != null) { InternetAddress[] recipients = new InternetAddress[bcc.size()]; for (int i = 0; i < bcc.size(); i++) recipients[i] = new InternetAddress(bcc.get(i)); msg.setRecipients(Message.RecipientType.BCC, recipients); } msg.setSubject(subject); msg.setHeader("X-Mailer", "Alvex Emailer"); msg.setSentDate(new Date()); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); if (body != null) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body, "utf-8", html ? "html" : "plain"); multipart.addBodyPart(messageBodyPart); } if (attachments != null) for (NodeRef att : attachments) { messageBodyPart = new MimeBodyPart(); String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME); messageBodyPart .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService))); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto()); t.connect(config.getUsername(), config.getPassword()); t.sendMessage(msg, msg.getAllRecipients()); t.close(); }
From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java
/** * Adds a mulitpart MimeBodyPart from an array of attachments *//*from ww w . j a v a 2 s. c o m*/ public static void addMultipartAttachment(MimeMultipart mp, StringToStringMap contentIds, List<Attachment> attachments) throws MessagingException { MimeMultipart multipart = new MimeMultipart("mixed"); long totalSize = 0; for (int c = 0; c < attachments.size(); c++) { Attachment att = attachments.get(c); String contentType = att.getContentType(); totalSize += att.getSize(); MimeBodyPart part = contentType.startsWith("text/") ? new MimeBodyPart() : new PreencodedMimeBodyPart("binary"); part.setDataHandler(new DataHandler(new AttachmentDataSource(att))); initPartContentId(contentIds, part, att, false); multipart.addBodyPart(part); } MimeBodyPart part = new PreencodedMimeBodyPart("binary"); if (totalSize > MAX_SIZE_IN_MEMORY_ATTACHMENT) { part.setDataHandler(new DataHandler(new MultipartAttachmentFileDataSource(multipart))); } else { part.setDataHandler(new DataHandler(new MultipartAttachmentDataSource(multipart))); } Attachment attachment = attachments.get(0); initPartContentId(contentIds, part, attachment, true); mp.addBodyPart(part); }
From source file:org.apache.camel.component.mail.MailBinding.java
protected void addBodyToMultipart(MailConfiguration configuration, MimeMultipart activeMultipart, Exchange exchange) throws MessagingException, IOException { BodyPart bodyMessage = new MimeBodyPart(); populateContentOnBodyPart(bodyMessage, configuration, exchange); activeMultipart.addBodyPart(bodyMessage); }
From source file:nl.nn.adapterframework.senders.MailSenderOld.java
protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType, String messageBase64, String charset, Collection<Recipient> recipients, Collection<Attachment> attachments) throws SenderException { StringBuffer sb = new StringBuffer(); if (recipients == null || recipients.size() == 0) { throw new SenderException("MailSender [" + getName() + "] has no recipients for message"); }/*w ww .j av a 2 s .com*/ if (StringUtils.isEmpty(from)) { from = defaultFrom; } if (StringUtils.isEmpty(subject)) { subject = defaultSubject; } log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject + "] to #recipients [" + recipients.size() + "]"); if (StringUtils.isEmpty(messageType)) { messageType = defaultMessageType; } if (StringUtils.isEmpty(messageBase64)) { messageBase64 = defaultMessageBase64; } try { if (log.isDebugEnabled()) { sb.append("MailSender [" + getName() + "] sending message "); sb.append("[smtpHost=" + smtpHost); sb.append("[from=" + from + "]"); sb.append("[subject=" + subject + "]"); sb.append("[threadTopic=" + threadTopic + "]"); sb.append("[text=" + message + "]"); sb.append("[type=" + messageType + "]"); sb.append("[base64=" + messageBase64 + "]"); } if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) { message = decodeBase64ToString(message); } // construct a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, charset); if (StringUtils.isNotEmpty(threadTopic)) { msg.setHeader("Thread-Topic", threadTopic); } Iterator iter = recipients.iterator(); boolean recipientsFound = false; while (iter.hasNext()) { Recipient recipient = (Recipient) iter.next(); String value = recipient.value; String type = recipient.type; Message.RecipientType recipientType; if ("cc".equalsIgnoreCase(type)) { recipientType = Message.RecipientType.CC; } else if ("bcc".equalsIgnoreCase(type)) { recipientType = Message.RecipientType.BCC; } else { recipientType = Message.RecipientType.TO; } msg.addRecipient(recipientType, new InternetAddress(value)); recipientsFound = true; if (log.isDebugEnabled()) { sb.append("[recipient [" + recipient + "]]"); } } if (!recipientsFound) { throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients"); } String messageTypeWithCharset; if (charset == null) { charset = System.getProperty("mail.mime.charset"); if (charset == null) { charset = System.getProperty("file.encoding"); } } if (charset != null) { messageTypeWithCharset = messageType + ";charset=" + charset; } else { messageTypeWithCharset = messageType; } log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]"); if (attachments == null || attachments.size() == 0) { //msg.setContent(message, messageType); msg.setContent(message, messageTypeWithCharset); } else { Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); //messageBodyPart.setContent(message, messageType); messageBodyPart.setContent(message, messageTypeWithCharset); multipart.addBodyPart(messageBodyPart); int counter = 0; iter = attachments.iterator(); while (iter.hasNext()) { counter++; Attachment attachment = (Attachment) iter.next(); Object value = attachment.getValue(); String name = attachment.getName(); if (StringUtils.isEmpty(name)) { name = getDefaultAttachmentName() + counter; } log.debug("found attachment [" + attachment + "]"); messageBodyPart = new MimeBodyPart(); messageBodyPart.setFileName(name); if (value instanceof DataHandler) { messageBodyPart.setDataHandler((DataHandler) value); } else { messageBodyPart.setText((String) value); } multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); } log.debug(sb.toString()); msg.setSentDate(new Date()); msg.saveChanges(); // send the message putOnTransport(msg); // return the mail in mail-safe from ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); byte[] byteArray = out.toByteArray(); return Misc.byteArrayToString(byteArray, "\n", false); } catch (Exception e) { throw new SenderException("MailSender got error", e); } }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from ww w .ja v a 2 s . c o m * * @param multipart DOCUMENT ME! * @param part DOCUMENT ME! * @param charset DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static void attach(MimeMultipart multipart, Part part, String charset) throws MessagingException { MimeBodyPart xbody = new MimeBodyPart(); PartDataSource xds = new PartDataSource(part); DataHandler xdh = new DataHandler(xds); xbody.setDataHandler(xdh); int xid = multipart.getCount() + 1; String xtext; // UNDONE //xbody.setContentLanguage( String ); // this could be language from Locale //xbody.setContentMD5( String md5 ); // don't know about this yet xtext = part.getDescription(); if (xtext == null) { xtext = "Part Attachment: " + xid; } xbody.setDescription(xtext, charset); xtext = getContentDisposition(part).getType(); xbody.setDisposition(xtext); xtext = MessageUtilities.getFileName(part); if ((xtext == null) || (xtext.length() < 1)) { xtext = "PART" + xid; } MessageUtilities.setFileName(xbody, xtext, charset); multipart.addBodyPart(xbody); }
From source file:be.ibridge.kettle.job.entry.mail.JobEntryMail.java
public Result execute(Result result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); File masterZipfile = null;//from w w w .j a v a2s . c o m // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { log.logError(toString(), "Unable to send the mail because the mail-server (SMTP host) is not specified"); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { protocol = "smtps"; } props.put("mail." + protocol + ".host", StringUtil.environmentSubstitute(server)); if (!Const.isEmpty(port)) props.put("mail." + protocol + ".port", StringUtil.environmentSubstitute(port)); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) props.put("mail.debug", "true"); if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(debug); try { // create a message Message msg = new MimeMessage(session); String email_address = StringUtil.environmentSubstitute(replyAddress); if (!Const.isEmpty(email_address)) { msg.setFrom(new InternetAddress(email_address)); } else { throw new MessagingException("reply e-mail address is not filled in"); } // Split the mail-address: space separated String destinations[] = StringUtil.environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); if (!Const.isEmpty(destinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = StringUtil.environmentSubstitute(destinationCc).split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } if (!Const.isEmpty(destinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = StringUtil.environmentSubstitute(destinationBCc).split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } msg.setSubject(StringUtil.environmentSubstitute(subject)); msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(StringUtil.environmentSubstitute(comment)).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append("Job:").append(Const.CR); messageText.append("-----").append(Const.CR); messageText.append("Name : ").append(parentJob.getJobMeta().getName()).append(Const.CR); messageText.append("Directory : ").append(parentJob.getJobMeta().getDirectory()).append(Const.CR); messageText.append("JobEntry : ").append(getName()).append(Const.CR); messageText.append(Const.CR); } if (includeDate) { Value date = new Value("date", new Date()); messageText.append("Message date: ").append(date.toString()).append(Const.CR).append(Const.CR); } if (!onlySendComment && result != null) { messageText.append("Previous result:").append(Const.CR); messageText.append("-----------------").append(Const.CR); messageText.append("Job entry nr : ").append(result.getEntryNr()).append(Const.CR); messageText.append("Errors : ").append(result.getNrErrors()).append(Const.CR); messageText.append("Lines read : ").append(result.getNrLinesRead()).append(Const.CR); messageText.append("Lines written : ").append(result.getNrLinesWritten()).append(Const.CR); messageText.append("Lines input : ").append(result.getNrLinesInput()).append(Const.CR); messageText.append("Lines output : ").append(result.getNrLinesOutput()).append(Const.CR); messageText.append("Lines updated : ").append(result.getNrLinesUpdated()).append(Const.CR); messageText.append("Script exit status : ").append(result.getExitStatus()).append(Const.CR); messageText.append("Result : ").append(result.getResult()).append(Const.CR); messageText.append(Const.CR); } if (!onlySendComment && (!Const.isEmpty(StringUtil.environmentSubstitute(contactPerson)) || !Const.isEmpty(StringUtil.environmentSubstitute(contactPhone)))) { messageText.append("Contact information :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append("Person to contact : ").append(StringUtil.environmentSubstitute(contactPerson)) .append(Const.CR); messageText.append("Telephone number : ").append(StringUtil.environmentSubstitute(contactPhone)) .append(Const.CR); messageText.append(Const.CR); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append("Path to this job entry:").append(Const.CR); messageText.append("------------------------").append(Const.CR); addBacktracking(jobTracker, messageText); } } Multipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part part1.setText(messageText.toString()); parts.addBodyPart(part1); if (includingFiles && result != null) { List resultFiles = result.getResultFilesList(); if (resultFiles != null && resultFiles.size() > 0) { if (!zipFiles) { // Add all files to the message... // for (Iterator iter = resultFiles.iterator(); iter.hasNext();) { ResultFile resultFile = (ResultFile) iter.next(); FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); log.logBasic(toString(), "Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + StringUtil.environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (Iterator iter = resultFiles.iterator(); iter.hasNext();) { ResultFile resultFile = (ResultFile) iter.next(); boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getURI()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( file.getContent().getInputStream()); int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } inputStream.close(); zipOutputStream.closeEntry(); log.logBasic(toString(), "Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { log.logError(toString(), "Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in th e data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(StringUtil.environmentSubstitute(Const.NVL(port, ""))), StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))); } else { transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } } catch (IOException e) { log.logError(toString(), "Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { log.logError(toString(), "Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { log.logError(toString(), " ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { log.logError(toString(), " " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { log.logError(toString(), " ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { log.logError(toString(), " " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { //System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { log.logError(toString(), " " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }
From source file:com.panet.imeta.trans.steps.mail.Mail.java
public void sendMail(Object[] r, String server, String port, String senderAddress, String senderName, String destination, String destinationCc, String destinationBCc, String contactPerson, String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject, String comment, String replyToAddresses) throws Exception { // Send an e-mail... // create some properties and get the default Session String protocol = "smtp"; if (meta.isUsingAuthentication()) { if (meta.getSecureConnectionType().equals("TLS")) { // Allow TLS authentication data.props.put("mail.smtp.starttls.enable", "true"); } else {/*from w w w. j a v a 2s . co m*/ protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version Unknown data.props.put("mail.smtps.quitwait", "false"); } } data.props.put("mail." + protocol + ".host", server); if (!Const.isEmpty(port)) data.props.put("mail." + protocol + ".port", port); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) data.props.put("mail.debug", "true"); if (meta.isUsingAuthentication()) data.props.put("mail." + protocol + ".auth", "true"); Session session = Session.getInstance(data.props); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set message priority if (meta.isUsePriority()) { String priority_int = "1"; if (meta.getPriority().equals("low")) priority_int = "3"; if (meta.getPriority().equals("normal")) priority_int = "2"; msg.setHeader("X-Priority", priority_int); //(String)int between 1= high and 3 = low. msg.setHeader("Importance", meta.getImportance()); //seems to be needed for MS Outlook. //where it returns a string of high /normal /low. } // set Email sender String email_address = senderAddress; if (!Const.isEmpty(email_address)) { // get sender name if (!Const.isEmpty(senderName)) email_address = senderName + '<' + email_address + '>'; msg.setFrom(new InternetAddress(email_address)); } else { throw new MessagingException(Messages.getString("Mail.Error.ReplyEmailNotFilled")); } // Set reply to if (!Const.isEmpty(replyToAddresses)) { // get replay to // Split the mail-address: space separated String[] reply_Address_List = replyToAddresses.split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) address[i] = new InternetAddress(reply_Address_List[i]); // To add the real reply-to msg.setReplyTo(address); } // Split the mail-address: space separated String destinations[] = destination.split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); String realdestinationCc = destinationCc; if (!Const.isEmpty(realdestinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = realdestinationCc.split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } String realdestinationBCc = destinationBCc; if (!Const.isEmpty(realdestinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = realdestinationBCc.split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } if (mailsubject != null) msg.setSubject(mailsubject); msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) messageText.append(comment).append(Const.CR).append(Const.CR); if (meta.getIncludeDate()) messageText.append(Messages.getString("Mail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) { messageText.append(Messages.getString("Mail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(Messages.getString("Mail.Log.Comment.PersonToContact") + " : ").append(contactPerson) .append(Const.CR); messageText.append(Messages.getString("Mail.Log.Comment.Tel") + " : ").append(contactPhone) .append(Const.CR); messageText.append(Const.CR); } data.parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part if (meta.isUseHTML()) { if (!Const.isEmpty(meta.getEncoding())) part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding()); else part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } else part1.setText(messageText.toString()); data.parts.addBodyPart(part1); // attached files if (meta.isDynamicFilename()) setAttachedFilesList(r, log); else setAttachedFilesList(null, log); msg.setContent(data.parts); Transport transport = null; try { transport = session.getTransport(protocol); if (meta.isUsingAuthentication()) { if (!Const.isEmpty(port)) { transport.connect(Const.NVL(server, ""), Integer.parseInt(Const.NVL(port, "")), Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, "")); } else { transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, "")); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } }
From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java
/**Compresses the payload using the ZLIB algorithm *//*from w w w . ja v a2s . c om*/ private MimeBodyPart compressPayload(Partner receiver, byte[] data, String contentType) throws SMIMEException, MessagingException { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType))); bodyPart.addHeader("Content-Type", contentType); if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) { bodyPart.addHeader("Content-Transfer-Encoding", "base64"); } else { bodyPart.addHeader("Content-Transfer-Encoding", "binary"); } SMIMECompressedGenerator generator = new SMIMECompressedGenerator(); if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) { generator.setContentTransferEncoding("base64"); } else { generator.setContentTransferEncoding("binary"); } return (generator.generate(bodyPart, SMIMECompressedGenerator.ZLIB)); }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from ww w . j a v a 2 s .c om * * @param multipart DOCUMENT ME! * @param file DOCUMENT ME! * @param charset DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static void attach(MimeMultipart multipart, File file, String charset) throws MessagingException { // UNDONE how to specify the character set of the file??? MimeBodyPart xbody = new MimeBodyPart(); FileDataSource xds = new FileDataSource(file); DataHandler xdh = new DataHandler(xds); xbody.setDataHandler(xdh); //System.out.println(xdh.getContentType()); // UNDONE // xbody.setContentLanguage( String ); // this could be language from Locale // xbody.setContentMD5( String md5 ); // don't know about this yet xbody.setDescription("File Attachment: " + file.getName(), charset); xbody.setDisposition(Part.ATTACHMENT); MessageUtilities.setFileName(xbody, file.getName(), charset); multipart.addBodyPart(xbody); }