List of usage examples for javax.mail Header getValue
public String getValue()
From source file:mitm.common.dlp.impl.MimeMessageTextExtractorImpl.java
private void extractMimeMessageMetaInfo(MimeMessage message, PartContext context) throws MessagingException { TextExtractorContext extractorContext = new TextExtractorContextImpl(); extractorContext.setEncoding(CharEncoding.US_ASCII); extractorContext.setName("headers"); StrBuilder sb = new StrBuilder(4096); try {//from w ww.java2 s.c om for (Enumeration<?> headerEnum = message.getAllHeaders(); headerEnum.hasMoreElements();) { Header header = (Header) headerEnum.nextElement(); if (header == null) { continue; } if (skipHeaders != null && skipHeaders.contains(StringUtils.lowerCase(header.getName()))) { continue; } sb.append(header.getName()).append(": ").appendln(HeaderUtils.decodeTextQuietly(header.getValue())); } } catch (MessagingException e) { /* * Fallback to raw headers */ for (Enumeration<?> headerEnum = message.getAllHeaderLines(); headerEnum.hasMoreElements();) { sb.appendln(headerEnum.nextElement()); } } byte[] headerBytes = MiscStringUtils.toUTF8Bytes(sb.toString()); RewindableInputStream input = new RewindableInputStream(new ByteArrayInputStream(headerBytes), MEM_THRESHOLD); ExtractedPart part = new ExtractedPartImpl(extractorContext, input, headerBytes.length); try { context.update(part, true /* add */); } catch (IOException e) { throw new MessagingException("Error adding part to context.", e); } }
From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java
/** * Process bounces.//from ww w. j a v a 2s . c om * * @param protocol the protocol * @param host the host * @param port the port * @param userName the user name * @param password the password */ public void processBounces(String protocol, String host, String port, String userName, String password) { Properties properties = getServerProperties(protocol, host, port); Session session = Session.getDefaultInstance(properties); List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes(); try { // connects to the message store Store store = session.getStore(protocol); System.out.println(userName); System.out.println(password); System.out.println(userName.length()); System.out.println(password.length()); //store.connect(userName, password); //TODO: ispraviti username i password da idu iz poziva a ne hardcoded store.connect("bojan.dimic@aquest-solutions.com", "bg181076"); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { BouncedEmail bouncedEmail = new BouncedEmail(); Message msg = messages[i]; Address[] fromAddress = msg.getFrom(); String from = fromAddress[0].toString(); String failedAddress = ""; Enumeration<?> headers = messages[i].getAllHeaders(); while (headers.hasMoreElements()) { Header h = (Header) headers.nextElement(); //System.out.println(h.getName() + ":" + h.getValue()); //System.out.println(""); String mID = h.getName(); if (mID.contains("X-Failed-Recipients")) { failedAddress = h.getValue(); } } String subject = msg.getSubject(); String toList = parseAddresses(msg.getRecipients(RecipientType.TO)); String ccList = parseAddresses(msg.getRecipients(RecipientType.CC)); String sentDate = msg.getSentDate().toString(); String contentType = msg.getContentType(); String messageContent = ""; if (contentType.contains("text/plain") || contentType.contains("text/html")) { try { Object content = msg.getContent(); if (content != null) { messageContent = content.toString(); } } catch (Exception ex) { messageContent = "[Error downloading content]"; ex.printStackTrace(); } } String bounceReason = "Unknown reason"; for (BounceCode bounceCode : bounceCodes) { if (messageContent.contains(bounceCode.getCode())) { bounceReason = bounceCode.getExplanation(); } } // if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";} // if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";} // // // enhanced bounce codes // if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";} // if(messageContent.contains("5.1.0")) {bounceReason="Other address status";} // if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";} // if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";} // if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";} // if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";} // if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";} // if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";} // if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";} // print out details of each message System.out.println("Message #" + (i + 1) + ":"); System.out.println("\t From: " + from); System.out.println("\t To: " + toList); System.out.println("\t CC: " + ccList); System.out.println("\t Subject: " + subject); System.out.println("\t Sent Date: " + sentDate); System.out.println("\t X-Failed-Recipients:" + failedAddress); System.out.println("\t Content Type:" + contentType); System.out.println("\t Bounce reason:" + bounceReason); //System.out.println("\t Message: " + messageContent); bouncedEmail.setEmail_address(failedAddress); bouncedEmail.setBounce_reason(bounceReason); //Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH); //String strDate = date.toString(); System.out.println(sentDate); Date dt = null; //Date nd = null; try { dt = formatter.parse(sentDate); //nd = sqlFormat.parse(dt.toString()); } catch (ParseException e) { e.printStackTrace(); } System.out.println("Date " + dt.toString()); //System.out.println("Date " + nd.toString()); System.out.println(new Timestamp(new Date().getTime())); bouncedEmail.setSend_date(dt); bouncedEmailDao.saveOrUpdate(bouncedEmail); } // disconnect folderInbox.close(false); store.close(); } catch (NoSuchProviderException ex) { System.out.println("No provider for protocol: " + protocol); ex.printStackTrace(); } catch (MessagingException ex) { System.out.println("Could not connect to the message store"); ex.printStackTrace(); } }
From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = new Result(nr); result.setResult(false);//from w w w . j a va2s . c om result.setNrErrors(1); FileObject fileObject = null; //Get system properties //Properties prop = System.getProperties(); Properties prop = new Properties(); //Create session object //Session sess = Session.getDefaultInstance(prop,null); Session sess = Session.getInstance(prop, null); sess.setDebug(true); try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); fileObject = KettleVFS.getFileObject(getRealOutputDirectory()); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists1.Label") + getRealOutputDirectory() + Messages.getString("JobGetMailsFromPOP.FolderNotExists2.Label")); } else { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); Store st = null; if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //Properties pop3Props = new Properties(); prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); prop.setProperty("mail.pop3.socketFactory.fallback", "false"); prop.setProperty("mail.pop3.port", getRealSSLPort()); prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); st = new POP3SSLStore(sess, url); st.connect(); } log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //Open default folder INBOX Folder f = st.getFolder("INBOX"); f.open(Folder.READ_ONLY); if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); } else { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder2.Label") + f.getMessageCount()); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder2.Label") + f.getNewMessageCount()); // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List current_file_POP = new ArrayList(); List current_filepath_POP = new ArrayList(); int nb_email_POP = 1; DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy"); String startpattern = "name"; if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { /*if(msg[i].isMimeType("text/plain")) { log.logDetailed(toString(), "Expediteur: "+msg[i].getFrom()[0]); log.logDetailed(toString(), "Sujet: "+msg[i].getSubject()); log.logDetailed(toString(), "Texte: "+(String)msg[i].getContent()); }*/ if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label") + msg_list[i].getFrom()[0]); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailSubject.Label") + msg_list[i].getSubject()); String localfilename_message = startpattern + "_" + dateFormat.format(new Date()) + "_" + (i + 1) + ".mail"; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LocalFilename1.Label") + localfilename_message + Messages.getString("JobGetMailsFromPOP.LocalFilename2.Label")); File filename_message = new File(getRealOutputDirectory(), localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = (Header) enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") .append(header_POP.getValue()).append("\r\n").toString().getBytes()); } os_filename.write("\r\n".getBytes()); InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); if (delete) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } // Close and exit if (f != null) f.close(false); if (st != null) st.close(); f = null; st = null; sess = null; result.setNrErrors(0); result.setResult(true); } } } catch (NoSuchProviderException e) { log.logError(toString(), "provider error: " + e.getMessage()); } catch (MessagingException e) { log.logError(toString(), "Message error: " + e.getMessage()); } catch (Exception e) { log.logError(toString(), "Inexpected error: " + e.getMessage()); } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } sess = null; } return result; }
From source file:com.adaptris.mail.MailReceiverCase.java
protected void printMessageInfo(MimeMessage msg) throws Exception { MessageParser mp = new MessageParser(msg); logger.debug("Got Message :- " + msg.getSubject()); logger.trace("With ID: " + mp.getMessageId()); Enumeration e = msg.getAllHeaders(); while (e.hasMoreElements()) { Header h = (Header) e.nextElement(); logger.trace("HeaderLine " + h.getName() + ": " + h.getValue()); }/*from ww w . j a v a2 s.com*/ if (mp.hasAttachments()) { while (mp.hasMoreAttachments()) { Attachment a = mp.nextAttachment(); logger.trace("Contains Attachment : " + a); } } }
From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java
@SuppressWarnings({ "unchecked" }) public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult(false);//from ww w. j a v a 2 s .c o m result.setNrErrors(1); //Get system properties Properties prop = new Properties(); prop.setProperty("mail.pop3s.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //Create session object Session sess = Session.getDefaultInstance(prop, null); sess.setDebug(true); FileObject fileObject = null; Store st = null; Folder f = null; try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); String realOutputFolder = getRealOutputDirectory(); fileObject = KettleVFS.getFileObject(realOutputFolder); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists.Label", realOutputFolder)); //$NON-NLS-1$ } else { if (fileObject.getType() == FileType.FOLDER) { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); //$NON-NLS-1$ // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.fallback", "false"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.port", getRealSSLPort()); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); //$NON-NLS-1$ URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); //$NON-NLS-1$ //$NON-NLS-2$ st = new POP3SSLStore(sess, url); st.connect(); } if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //$NON-NLS-1$ //Open the INBOX FOLDER // For POP3, the only folder available is the INBOX. f = st.getFolder("INBOX"); //$NON-NLS-1$ if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); //$NON-NLS-1$ } else { // Open folder if (delete) f.open(Folder.READ_WRITE); else f.open(Folder.READ_ONLY); Message messageList[] = f.getMessages(); if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder.Label", f.getName(), //$NON-NLS-1$ String.valueOf(messageList.length))); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder.Label", //$NON-NLS-1$ f.getName(), String.valueOf(f.getUnreadMessageCount()))); } // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List<File> current_file_POP = new ArrayList<File>(); List<String> current_filepath_POP = new ArrayList<String>(); int nb_email_POP = 1; String startpattern = "name"; //$NON-NLS-1$ if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label", //$NON-NLS-1$ msg_list[i].getFrom()[0].toString())); log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.EmailSubject.Label", msg_list[i].getSubject())); //$NON-NLS-1$ } String localfilename_message = startpattern + "_" //$NON-NLS-1$ + StringUtil.getFormattedDateTimeNow(true) + "_" + (i + 1) + ".mail"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDetailed()) log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.LocalFilename.Label", localfilename_message)); //$NON-NLS-1$ File filename_message = new File(realOutputFolder, localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration<Header> enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") //$NON-NLS-1$ .append(header_POP.getValue()).append("\r\n").toString().getBytes()); //$NON-NLS-1$ } os_filename.write("\r\n".getBytes()); //$NON-NLS-1$ InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); // Check attachments Object content = msg_POP.getContent(); if (content instanceof Multipart) { handleMultipart(realOutputFolder, (Multipart) content); } // Check if mail has to be deleted if (delete) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); //$NON-NLS-1$ msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } result.setNrErrors(0); result.setResult(true); } } else { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.Error.NotAFolder", realOutputFolder)); } } } catch (NoSuchProviderException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.ProviderException", e.getMessage())); //$NON-NLS-1$ } catch (MessagingException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.MessagingException", e.getMessage())); //$NON-NLS-1$ } catch (Exception e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.GeneralException", e.getMessage())); //$NON-NLS-1$ } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } //close the folder, passing in a true value to expunge the deleted message try { if (f != null) f.close(true); if (st != null) st.close(); } catch (Exception e) { log.logError(toString(), e.getMessage()); } // free memory f = null; st = null; sess = null; } return result; }
From source file:com.duroty.application.mail.manager.SendManager.java
/** * DOCUMENT ME!//from www . j av a 2s . c o m * * @param hsession DOCUMENT ME! * @param session DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param ideIdint DOCUMENT ME! * @param to DOCUMENT ME! * @param cc DOCUMENT ME! * @param bcc DOCUMENT ME! * @param subject DOCUMENT ME! * @param body DOCUMENT ME! * @param attachments DOCUMENT ME! * @param isHtml DOCUMENT ME! * @param charset DOCUMENT ME! * @param headers DOCUMENT ME! * @param priority DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint, String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml, String charset, InternetHeaders headers, String priority) throws MailException { try { if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } if ((body == null) || body.trim().equals("")) { body = " "; } Email email = null; if (isHtml) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charset); Users user = getUser(hsession, repositoryName); Identity identity = getIdentity(hsession, ideIdint, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null); InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null); InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _to); email.setTo(aux); } if ((_cc != null) && (_cc.length > 0)) { HashSet aux = new HashSet(_cc.length); Collections.addAll(aux, _cc); email.setCc(aux); } if ((_bcc != null) && (_bcc.length > 0)) { HashSet aux = new HashSet(_bcc.length); Collections.addAll(aux, _bcc); email.setBcc(aux); } email.setSubject(subject); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } if ((attachments != null) && (attachments.size() > 0)) { for (int i = 0; i < attachments.size(); i++) { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { MailPartObj obj = (MailPartObj) attachments.get(i); File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); if (email instanceof MultiPartEmail) { ((MultiPartEmail) email).attach(attachment); } } catch (Exception ex) { } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } } if (headers != null) { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) { email.addHeader(xheader.getName(), xheader.getValue()); } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) { email.addHeader(xheader.getName(), xheader.getValue()); } } } if (priority != null) { if (priority.equals("high")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "1"); } else if (priority.equals("low")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "5"); } } if (email instanceof HtmlEmail) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeDraftMessage(getId(), mime, user); } catch (MailException e) { throw e; } catch (Exception e) { throw new MailException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.duroty.application.mail.manager.SendManager.java
/** * DOCUMENT ME!/* w ww .ja v a 2s. c o m*/ * * @param hsession DOCUMENT ME! * @param session DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param identity DOCUMENT ME! * @param to DOCUMENT ME! * @param cc DOCUMENT ME! * @param bcc DOCUMENT ME! * @param subject DOCUMENT ME! * @param body DOCUMENT ME! * @param attachments DOCUMENT ME! * @param isHtml DOCUMENT ME! * @param charset DOCUMENT ME! * @param headers DOCUMENT ME! * @param priority DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public void send(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint, String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml, String charset, InternetHeaders headers, String priority) throws MailException { try { if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } if ((body == null) || body.trim().equals("")) { body = " "; } Email email = null; if (isHtml) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charset); Users user = getUser(hsession, repositoryName); Identity identity = getIdentity(hsession, ideIdint, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null); InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null); InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _to); email.setTo(aux); } if ((_cc != null) && (_cc.length > 0)) { HashSet aux = new HashSet(_cc.length); Collections.addAll(aux, _cc); email.setCc(aux); } if ((_bcc != null) && (_bcc.length > 0)) { HashSet aux = new HashSet(_bcc.length); Collections.addAll(aux, _bcc); email.setBcc(aux); } email.setSubject(subject); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } if ((attachments != null) && (attachments.size() > 0)) { for (int i = 0; i < attachments.size(); i++) { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { MailPartObj obj = (MailPartObj) attachments.get(i); File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); if (email instanceof MultiPartEmail) { ((MultiPartEmail) email).attach(attachment); } } catch (Exception ex) { } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } } String mid = getId(); if (headers != null) { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) { email.addHeader(xheader.getName(), xheader.getValue()); } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) { email.addHeader(xheader.getName(), xheader.getValue()); } } } else { email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); } if (priority != null) { if (priority.equals("high")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "1"); } else if (priority.equals("low")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "5"); } } if (email instanceof HtmlEmail) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.saveSentMessage(mid, mime, user); Thread thread = new Thread(new SendMessageThread(email)); thread.start(); } catch (MailException e) { throw e; } catch (Exception e) { throw new MailException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/* w ww . ja va 2 s.c o m*/ * * @param message DOCUMENT ME! * @param headers DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static void addHeaders(Message message, InternetHeaders headers) throws MessagingException { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); message.addHeader(xheader.getName(), xheader.getValue()); } }
From source file:com.duroty.utils.mail.MessageUtilities.java
public static InternetHeaders getHeadersWithFrom(Message message) throws MessagingException { Header xheader; InternetHeaders xheaders = new InternetHeaders(); Enumeration xe = message.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); xheaders.addHeader(xheader.getName(), xheader.getValue()); }/*from ww w . j av a 2 s.c o m*/ return xheaders; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/*from w w w . j a va 2s . c o m*/ * * @param message DOCUMENT ME! * * @return DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static InternetHeaders getHeaders(Message message) throws MessagingException { Header xheader; InternetHeaders xheaders = new InternetHeaders(); Enumeration xe = message.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); if (!xheader.getName().startsWith("From ")) { xheaders.addHeader(xheader.getName(), xheader.getValue()); } } return xheaders; }