List of usage examples for javax.mail Message setHeader
public void setHeader(String header_name, String header_value) throws MessagingException;
From source file:com.panet.imeta.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); File masterZipfile = null;//w w w . j a v a 2 s . c om // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version // Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) props.put("mail." + protocol + ".port", 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); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int // between 1= high // and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) sender_address = sender_name + '<' + sender_address + '>'; msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).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]); msg.setReplyTo(address); } // Split the mail-address: space separated String destinations[] = 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[] = 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[] = 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); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR); messageText.append("-----").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getDirectory()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + " : ").append(getName()) .append(Const.CR); messageText.append(Const.CR); } if (includeDate) { messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); } if (!onlySendComment && result != null) { messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR); messageText.append("-----------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(Const.CR); messageText.append(Const.CR); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + " : ") .append(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(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":") .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 if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else part1.setText(messageText.toString()); parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { 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(file.getName().getBaseName()); // 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 + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { 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().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into // this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); 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(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), environmentSubstitute(Const.NVL(authenticationPassword, ""))); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), 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.funambol.email.items.manager.ImapEntityManager.java
/** * * * @param FID folder id String//from w w w .j a va 2 s.co m * @param LUID String * @param emailToAdd Email * @param filter EmailFilter * @param funSignature String * @param from String * @param firstname String * @param lastname String * @param username String * @param source_uri String * @param principalId long * @return Email * @throws EntityException */ public Email addEmail(String FID, String LUID, Email emailToAdd, Map serverItems, EmailFilter filter, String funSignature, String from, String firstname, String lastname, String username, String source_uri, long principalId) throws EntityException, SendingException, RefusedItemException { IMAPFolder f = null; String fullpath = null; // the emailItem could be null // i.e. the client send only the read property FlagProperties fp = Utility.getFlags(emailToAdd); if (emailToAdd != null && emailToAdd.getEmailItem() != null && Def.ENCODE_QUOTED_PRINTABLE.equals(emailToAdd.getEmailItem().getEncoding())) { try { emailToAdd.getEmailItem().setPropertyValue( Utility.decode(emailToAdd.getEmailItem().getStringRFC2822(), Def.ENCODE_QUOTED_PRINTABLE)); emailToAdd.getEmailItem().setEncoding(null); } catch (MessagingException e) { throw new EntityException(e); } } try { if (FID.equalsIgnoreCase(Def.FOLDER_OUTBOX_ID)) { // OUTBOX - sending procedure (email with id starts with "O") FID = Def.FOLDER_SENT_ID; // convert Email into Message (javaMail) Message msg = createMessage(this.imsw.getSession(), emailToAdd, FID, false, fp); // save message-ID String messageID = Utility.getHeaderMessageID(msg); // send message Message newMsg = null; try { newMsg = sendEmail(msg, this.imsw.getSession(), funSignature, from, firstname, lastname); } catch (SendingException se) { throw new SendingException(se); } if (newMsg != null) { if (messageID != null) { newMsg.setHeader(Def.HEADER_MESSAGE_ID, messageID); } newMsg.setFlag(Flags.Flag.SEEN, true); } else { if (messageID != null) { msg.setHeader(Def.HEADER_MESSAGE_ID, messageID); } } if (Def.SERVER_TYPE_AOL.equals(this.serverType) || Def.SERVER_TYPE_GMAIL.equals(this.serverType)) { // // The email is stored in the SENT folder by the AOL server // and Gmail imap. // // don't save the email in the sent folder emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID)); String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(LUID), String.valueOf(0)); emailToAdd.setUID(new Property(GUID)); // if the item is not saved in the sent folder the system // doesn't add it into the servetItems list return emailToAdd; } else { // the SENT folder could be disable // if it's enabled the system adds the item in the sent // folder of the Mail Server // get Sent folder name fullpath = this.ied.getFullPathFromFID(FID, source_uri, principalId, username); if (fullpath == null) { emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID)); String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(LUID), String.valueOf(0)); emailToAdd.setUID(new Property(GUID)); return emailToAdd; } // open Sent Folder on mail server f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath); if (!f.exists()) { emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID)); String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(LUID), String.valueOf(0)); emailToAdd.setUID(new Property(GUID)); return emailToAdd; } timeStart = System.currentTimeMillis(); f.open(Folder.READ_WRITE); long uid = -1; if (this.serverType.equals(Def.SERVER_TYPE_COURIER)) { if (newMsg != null) { uid = this.ied.addEmailByNextUID(f, newMsg); } else { uid = this.ied.addEmailByNextUID(f, msg); } } else { if (newMsg != null) { uid = this.ied.addEmailByListener(f, newMsg); } else { uid = this.ied.addEmailByListener(f, msg); } } emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID)); long uidv = f.getUIDValidity(); String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(uid), String.valueOf(uidv)); emailToAdd.setUID(new Property(GUID)); // create the object to add in db and in serverItems SyncItemInfo sii = createInfo(GUID, msg, null, Def.PROTOCOL_IMAP); // add email to the servetItems list this.ied.addItemInServerItems(sii, serverItems); return emailToAdd; } } else { /** * this procedure should be tested with client that syncs * items into the the folders: INBOX - SENT - DRAFT - TRASH * At the moment the Funambol client doesn't sync the * previous folders. */ // INBOX - SENT - DRAFT - TRASH if (this.isFolderActive(FID, filter)) { fullpath = this.ied.getFullPathFromFID(FID, source_uri, principalId, username); if (fullpath == null) { return emailToAdd; } f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath); if (!f.exists()) { //emailToAdd.setUID(new Property(LUID)); return emailToAdd; } // convert Email into Message (javaMail) Message msg = createMessage(this.imsw.getSession(), emailToAdd, FID, false, fp); checkIfItHasToBeRefused(msg); // add in the folder of the Mail Server timeStart = System.currentTimeMillis(); f.open(Folder.READ_WRITE); long uid = -1; if (this.serverType.equals(Def.SERVER_TYPE_COURIER)) { uid = this.ied.addEmailByNextUID(f, msg); } else { uid = this.ied.addEmailByListener(f, msg); } long uidv = f.getUIDValidity(); String GUID = Utility.createIMAPGUID(FID, String.valueOf(uid), String.valueOf(uidv)); emailToAdd.setUID(new Property(GUID)); // create the object to add in db and in serverItems SyncItemInfo sii = createInfo(GUID, msg, null, Def.PROTOCOL_IMAP); if (FID.equalsIgnoreCase(Def.FOLDER_INBOX_ID)) { // add email into the inbox table this.ied.addEmailInDB(sii, username, Def.PROTOCOL_IMAP); } // add email to the servetItems list this.ied.addItemInServerItems(sii, serverItems); return emailToAdd; } else { return emailToAdd; } } } catch (MessagingException me) { throw new EntityException(me); } catch (SendingException e) { throw new SendingException(e); } finally { if (f != null) { try { if (f.isOpen()) { f.close(true); timeStop = System.currentTimeMillis(); if (log.isTraceEnabled()) { log.trace("insertItem Execution Time: " + (timeStop - timeStart) + " ms"); } } } catch (MessagingException me) { throw new EntityException(me); } } } }
From source file:com.sonicle.webtop.mail.Service.java
private Message _saveMessage(SimpleMessage msg, List<JsAttachment> attachments, FolderCache fc) throws Exception { UserProfile profile = environment.getProfile(); String sender = profile.getEmailAddress(); String name = profile.getDisplayName(); Identity from = msg.getFrom(); String replyto = getAccount(from).getReplyTo(); if (from != null) { sender = from.getEmail();/*from ww w . j av a 2s . c o m*/ name = from.getDisplayName(); if (replyto == null || replyto.trim().length() == 0) replyto = sender; } msg.setReplyTo(replyto); if (name != null && name.length() > 0) { sender = name + " <" + sender + ">"; } /*ArrayList<Attachment> origattachments = getAttachments(msg.getId()); ArrayList<Attachment> attachments = new ArrayList<Attachment>(); for (String attname : attnames) { for (Attachment att : origattachments) { if (att.getFile().getName().equals(attname)) { attachments.add(att); //Service.logger.debug("Adding attachment : "+attname+" -> "+att.getName()); break; } } }*/ Message newmsg = createMessage(sender, msg, attachments, true); newmsg.setHeader("Sonicle-draft", "true"); //FolderCache fc=getFolderCache(profile.getFolderDrafts()); //newmsg.writeTo(new FileOutputStream("C:/Users/gbulfon/Desktop/TEST.eml")); fc.save(newmsg); clearCloudAttachments(msg.getId()); return newmsg; }
From source file:de.innovationgate.wgpublisher.WGACore.java
public void send(WGAMailNotification notification) { WGAMailConfiguration config = getMailConfig(); if (config != null && config.isEnableAdminNotifications()) { try {//from w w w . ja va 2 s . com Message msg = new MimeMessage(config.createMailSession()); // set recipient and from address String toAddress = config.getToAddress(); if (toAddress == null) { getLog().error( "Unable to send wga admin notification because no recipient address is configured"); return; } msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); InternetAddress[] fromAddr = new InternetAddress[1]; fromAddr[0] = new InternetAddress(config.getFromAddress()); msg.addFrom(fromAddr); msg.setSentDate(new Date()); InetAddress localMachine = InetAddress.getLocalHost(); String hostname = localMachine.getHostName(); String serverName = getWgaConfiguration().getServerName(); if (serverName == null) { serverName = hostname; } msg.setSubject(notification.getSubject()); msg.setHeader(WGAMailNotification.HEADERFIELD_TYPE, notification.getType()); MimeMultipart content = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); StringBuffer strBody = new StringBuffer(); strBody.append("<html><head></head><body style=\"color:#808080\">"); strBody.append(notification.getMessage()); String rootURL = getWgaConfiguration().getRootURL(); if (rootURL != null) { //strBody.append("<br><br>"); strBody.append("<p><a href=\"" + rootURL + "/plugin-admin\">" + WGABrand.getName() + " admin client ...</a></p>"); } // append footer strBody.append("<br><br><b>System information:</b><br><br>"); strBody.append("<b>Server:</b> " + serverName + " / " + WGACore.getReleaseString() + "<br>"); strBody.append("<b>Host:</b> " + hostname + "<br>"); strBody.append("<b>Operation System:</b> " + System.getProperty("os.name") + " Version " + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")<br>"); strBody.append("<b>Java virtual machine:</b> " + System.getProperty("java.vm.name") + " Version " + System.getProperty("java.vm.version") + " (" + System.getProperty("java.vm.vendor") + ")"); strBody.append("</body></html>"); body.setText(strBody.toString()); body.setHeader("MIME-Version", "1.0"); body.setHeader("Content-Type", "text/html"); content.addBodyPart(body); AppLog appLog = WGA.get(this).service(AppLog.class); if (notification.isAttachLogfile()) { MimeBodyPart attachmentBody = new MimeBodyPart(); StringWriter applog = new StringWriter(); int applogSize = appLog.getLinesCount(); int offset = applogSize - notification.getLogfileLines(); if (offset < 0) { offset = 1; } appLog.writePage(offset, notification.getLogfileLines(), applog, LogLevel.LEVEL_INFO, false); attachmentBody.setDataHandler(new DataHandler(applog.toString(), "text/plain")); attachmentBody.setFileName("wga.log"); content.addBodyPart(attachmentBody); } msg.setContent(content); // Send mail Thread mailThread = new Thread(new AsyncMailSender(msg), "WGAMailSender"); mailThread.start(); } catch (Exception e) { getLog().error("Unable to send wga admin notification.", e); } } }
From source file:com.sonicle.webtop.mail.Service.java
private SimpleMessage getForwardMsg(long id, Message msg, boolean richContent, String fromtitle, String totitle, String cctitle, String datetitle, String subjecttitle, boolean attached) { Message forward = new MimeMessage(mainAccount.getMailSession()); if (!attached) { try {/*w w w . j a v a 2s . co m*/ StringBuffer htmlsb = new StringBuffer(); StringBuffer textsb = new StringBuffer(); boolean isHtml = appendReplyParts(msg, htmlsb, textsb, null); // Service.logger.debug("isHtml="+isHtml); // Service.logger.debug("richContent="+richContent); String html = "<HTML><BODY>" + htmlsb.toString() + "</BODY></HTML>"; if (!richContent) { forward.setText(getForwardBody(msg, textsb.toString(), SimpleMessage.FORMAT_TEXT, false, fromtitle, totitle, cctitle, datetitle, subjecttitle)); } else if (!isHtml) { forward.setText(getForwardBody(msg, textsb.toString(), SimpleMessage.FORMAT_PREFORMATTED, false, fromtitle, totitle, cctitle, datetitle, subjecttitle)); } else { forward.setText(MailUtils.removeMSWordShit(getForwardBody(msg, html, SimpleMessage.FORMAT_HTML, true, fromtitle, totitle, cctitle, datetitle, subjecttitle))); } } catch (Exception exc) { Service.logger.error("Exception", exc); } } try { String msgid = null; String vh[] = msg.getHeader("Message-ID"); if (vh != null) { msgid = vh[0]; } if (msgid != null) { forward.setHeader("Forwarded-From", msgid); } } catch (MessagingException exc) { Service.logger.error("Exception", exc); } SimpleMessage fwd = new SimpleMessage(id, forward); fwd.setTo(""); // Update appropriate subject // Fwd: subject try { String subject = msg.getSubject(); if (subject == null) { subject = ""; } if (!subject.toLowerCase().startsWith("fwd: ")) { fwd.setSubject("Fwd: " + subject); } else { fwd.setSubject(msg.getSubject()); } } catch (MessagingException e) { Service.logger.error("Exception", e); // Service.logger.debug("*** SimpleMessage: " +e); } return fwd; }
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Fill the body of a message already created. * The result message depends on the information given. * //from ww w.j a va 2s. c o m * @param message * @param text * @param html * @param parts * @return The composed message * @throws MessagingException * @throws IOException */ @SuppressWarnings("rawtypes") public static Message composeMessage(Message message, String text, String html, List parts) throws MessagingException, IOException { MimeBodyPart txtPart = null; MimeBodyPart htmlPart = null; MimeMultipart mimeMultipart = null; if (text == null && html == null) { text = ""; } if (text != null) { txtPart = new MimeBodyPart(); txtPart.setContent(text, "text/plain"); } if (html != null) { htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html"); } if (html != null && text != null) { mimeMultipart = new MimeMultipart(); mimeMultipart.setSubType("alternative"); mimeMultipart.addBodyPart(txtPart); mimeMultipart.addBodyPart(htmlPart); } if (parts == null || parts.isEmpty()) { if (mimeMultipart != null) { message.setContent(mimeMultipart); } else if (html != null) { message.setText(html); message.setHeader("Content-type", "text/html"); } else if (text != null) { message.setText(text); } } else { MimeBodyPart bodyPart = new MimeBodyPart(); if (mimeMultipart != null) { bodyPart.setContent(mimeMultipart); } else if (html != null) { bodyPart.setText(html); bodyPart.setHeader("Content-type", "text/html"); } else if (text != null) { bodyPart.setText(text); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); for (Object attachment : parts) { if (attachment instanceof FileItem) { multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment)); } else { multipart.addBodyPart((BodyPart) attachment); } } message.setContent(multipart); } message.saveChanges(); return message; }
From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java
/** * Fill the body of a message already created. * The result message depends on the information given. * * @param message/*w w w . j a va2 s .c o m*/ * @param text * @param html * @param parts * @return The composed message * @throws MessagingException * @throws IOException */ @SuppressWarnings("rawtypes") public static Message composeMessage(Message message, String text, String html, List parts) throws MessagingException, IOException { MimeBodyPart txtPart = null; MimeBodyPart htmlPart = null; MimeMultipart mimeMultipart = null; if (text == null && html == null) { text = ""; } if (text != null) { txtPart = new MimeBodyPart(); txtPart.setContent(text, "text/plain; charset=UTF-8"); } if (html != null) { htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html; charset=UTF-8"); } if (html != null && text != null) { mimeMultipart = new MimeMultipart(); mimeMultipart.setSubType("alternative"); mimeMultipart.addBodyPart(txtPart); mimeMultipart.addBodyPart(htmlPart); } if (parts == null || parts.isEmpty()) { if (mimeMultipart != null) { message.setContent(mimeMultipart); } else if (html != null) { message.setText(html); message.setHeader("Content-type", "text/html"); } else if (text != null) { message.setText(text); } } else { MimeBodyPart bodyPart = new MimeBodyPart(); if (mimeMultipart != null) { bodyPart.setContent(mimeMultipart); } else if (html != null) { bodyPart.setText(html); bodyPart.setHeader("Content-type", "text/html"); } else if (text != null) { bodyPart.setText(text); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); for (Object attachment : parts) { if (attachment instanceof FileItem) { multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment)); } else { multipart.addBodyPart((BodyPart) attachment); } } message.setContent(multipart); } message.saveChanges(); return message; }
From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java
/** * 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/*w ww .j a va2 s . c o m*/ * 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); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(first)); message.setText(IOUtils.toString(is)); } finally { IOUtils.closeQuietly(is); } } 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) ((TestElementProperty) headerFields.get(i)).getObjectValue(); message.setHeader(argument.getName(), argument.getValue()); } message.saveChanges(); return message; }
From source file:org.apache.nifi.processors.standard.PutEmail.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final FlowFile flowFile = session.get(); if (flowFile == null) { return;/*from w ww . jav a2 s.co m*/ } final Properties properties = this.getMailPropertiesFromFlowFile(context, flowFile); final Session mailSession = this.createMailSession(properties); final Message message = new MimeMessage(mailSession); final ComponentLog logger = getLogger(); try { message.addFrom(toInetAddresses(context, flowFile, FROM)); message.setRecipients(RecipientType.TO, toInetAddresses(context, flowFile, TO)); message.setRecipients(RecipientType.CC, toInetAddresses(context, flowFile, CC)); message.setRecipients(RecipientType.BCC, toInetAddresses(context, flowFile, BCC)); message.setHeader("X-Mailer", context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions(flowFile).getValue()); message.setSubject(context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue()); String messageText = context.getProperty(MESSAGE).evaluateAttributeExpressions(flowFile).getValue(); if (context.getProperty(INCLUDE_ALL_ATTRIBUTES).asBoolean()) { messageText = formatAttributes(flowFile, messageText); } String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions(flowFile) .getValue(); message.setContent(messageText, contentType); message.setSentDate(new Date()); if (context.getProperty(ATTACH_FILE).asBoolean()) { final MimeBodyPart mimeText = new PreencodedMimeBodyPart("base64"); mimeText.setDataHandler(new DataHandler(new ByteArrayDataSource( Base64.encodeBase64(messageText.getBytes("UTF-8")), contentType + "; charset=\"utf-8\""))); final MimeBodyPart mimeFile = new MimeBodyPart(); session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream stream) throws IOException { try { mimeFile.setDataHandler( new DataHandler(new ByteArrayDataSource(stream, "application/octet-stream"))); } catch (final Exception e) { throw new IOException(e); } } }); mimeFile.setFileName(flowFile.getAttribute(CoreAttributes.FILENAME.key())); MimeMultipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeText); multipart.addBodyPart(mimeFile); message.setContent(multipart); } send(message); session.getProvenanceReporter().send(flowFile, "mailto:" + message.getAllRecipients()[0].toString()); session.transfer(flowFile, REL_SUCCESS); logger.info("Sent email as a result of receiving {}", new Object[] { flowFile }); } catch (final ProcessException | MessagingException | IOException e) { context.yield(); logger.error("Failed to send email for {}: {}; routing to failure", new Object[] { flowFile, e.getMessage() }, e); session.transfer(flowFile, REL_FAILURE); } }
From source file:org.blue.star.plugins.send_mail.java
public boolean execute_check() { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); if (smtpAuth) { props.put("mail.smtp.auth", "true"); }// w w w. j a va2 s .c o m Session session = Session.getInstance(props, null); SMTPTransport transport = null; // if (debug) // session.setDebug(true); // construct the message try { Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (subject != null) msg.setSubject(subject); msg.setHeader("X-Mailer", "blue-send-mail"); msg.setSentDate(new Date()); msg.setText(message.replace("\\n", "\n").replace("\\t", "\t")); transport = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp"); if (smtpAuth) transport.connect(smtpServer, smtpUser, smtpPass); else transport.connect(); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (MessagingException mE) { mE.printStackTrace(); this.state = common_h.STATE_CRITICAL; this.text = mE.getMessage(); return false; } finally { try { transport.close(); } catch (Exception e) { } } state = common_h.STATE_OK; text = "Message Sent!"; return true; }