List of usage examples for javax.mail.internet MimeMessage MimeMessage
protected MimeMessage(Folder folder, int msgnum)
From source file:com.spartasystems.holdmail.smtp.SMTPHandler.java
@Override public void done() { try {/*from w w w .ja v a 2s.co m*/ Session s = Session.getDefaultInstance(new Properties()); MimeMessage mimeMsg = new MimeMessage(s, new ByteArrayInputStream(data)); // set any data from the mimemessage itself MessageHeaders headers = getHeaders(mimeMsg); Message message = new Message(0, mimeMsg.getMessageID(), headers.get("Subject"), this.senderEmail, new Date(), senderHost, this.data.length, IOUtils.toString(data, CharEncoding.UTF_8), this.recipients, headers); messageService.saveMessage(message); logger.info("Stored SMTP message from " + message.getSenderEmail() + " to " + StringUtils.join(message.getRecipients(), ",")); } catch (Exception e) { logger.error("Couldn't handle message: " + e.getMessage(), e); } }
From source file:com.riq.MailHandlerServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("Inside MailServlet doPost"); // TODO get path information to determine target Department for this email PersistenceManager pm = PMF.get().getPersistenceManager(); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try {//from w ww . j a v a2 s .c o m MimeMessage msg = new MimeMessage(session, req.getInputStream()); Address sender = msg.getFrom()[0]; Address replyTo = msg.getReplyTo()[0]; // DEBUG // log.info("Message Class: " + msg.getClass()); // log.info("Message Stream: " + msg.getInputStream()); // log.info("Message RawStream: " + msg.getRawInputStream()); // log.info("Message Flags: " + msg.getFlags()); // log.info("Message Content: " + msg.getContent().toString()); // log.info("Message ContentID: " + msg.getContentID()); // log.info("Message ContentMD: " + msg.getContentMD5()); // log.info("Message ContentType: " + msg.getContentType()); // log.info("Message Description: " + msg.getDescription()); // log.info("Message Disposition: " + msg.getDisposition()); // log.info("Message Encoding: " + msg.getEncoding()); // log.info("Message Filename: " + msg.getFileName()); // log.info("Message Line Count: " + msg.getLineCount()); // log.info("Message ID: " + msg.getMessageID()); // log.info("Message Number: " + msg.getMessageNumber()); // log.info("Message Size: " + msg.getSize()); // log.info("Message Subject: " + msg.getSubject()); // log.info("Message RawInputStream: " + msg.getRawInputStream().toString()); // log.info("Message ReplyTo: " + replyTo); // log.info("Message Sender: " + sender.toString()); // log.info("Request URL TO: " + getServletContext()); String alertMsgString = getText(msg); alertMsgString = alertMsgString.replaceAll("Begin forwarded message:", ""); alertMsgString = alertMsgString.replaceAll("Forwarded message", ""); alertMsgString = alertMsgString.replaceAll("Dispatch@co.morris.nj.us", ""); alertMsgString = alertMsgString.replaceAll("Date:", ""); alertMsgString = alertMsgString.replaceAll(">", ""); alertMsgString = alertMsgString.replaceAll("::", "-"); alertMsgString = alertMsgString.replaceAll("< ", ""); alertMsgString = alertMsgString.replaceAll("----------", ""); alertMsgString = alertMsgString.replaceAll("Subject:", ""); alertMsgString = alertMsgString.replaceAll("To:", ""); alertMsgString = alertMsgString.replaceAll("From:", ""); // Added to grab gmail confirmations // alertMsgString = alertMsgString.substring(50, 300); try { String queryDept = "select from " + Department.class.getName() + // TODO: johnreilly workaround for getting allRecipients... // " where dispatchId == '" + toAddressDigitsOnly + "' " + " where dispatchId == '2599' " + " && fromEmail == '" + sender + "' "; log.info("queryDept: " + queryDept); List<Department> depts = (List<Department>) pm.newQuery(queryDept).execute(); if (depts.size() != 0) { for (Department d : depts) { // need to filter further e.g. last two hours String queryAlert = "select from " + Alert.class.getName() + " where deptId == " + depts.get(0).getid() + " && messageId == '" + msg.getMessageID() + "' "; log.info("queryAlert: " + queryAlert); List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute(); log.info("queryAlert Result Qty: " + alerts.size()); if (alerts.size() == 0) { riqGeocode(alertMsgString); // geocode the address from the Alert Map<String, String> geoResults = riqGeocode(alertMsgString); log.info("lat print: " + geoResults.get("lat")); log.info("lng print: " + geoResults.get("lng")); // create the alert Long deptId = depts.get(0).getid(); Long timeStamp = System.currentTimeMillis(); Alert a = new Alert(deptId, timeStamp, alertMsgString.trim(), sender.toString(), "Active", "", geoResults.get("lat"), geoResults.get("lng"), msg.getMessageID()); pm.makePersistent(a); // query to get id of this alert String queryThisAlert = "select from " + Alert.class.getName() + " where deptId == " + deptId + " " + " && timeStamp == " + timeStamp; log.info("queryThisAlert: " + queryThisAlert); List<Alert> thisAlert = (List<Alert>) pm.newQuery(queryThisAlert).execute(); log.info("queryCurrentAlert Result Qty: " + thisAlert.size()); // create Tracking records for "special" Locations String querySpecialLocs = "select from " + Location.class.getName() + " where special == 'yes' && deptId == " + deptId; log.info("querySpecialLocs: " + querySpecialLocs); List<Location> specialLocs = (List<Location>) pm.newQuery(querySpecialLocs).execute(); log.info("querySpecialLocs qty: " + specialLocs.size()); for (Location specL : specialLocs) { Tracking tSL = new Tracking(deptId, thisAlert.get(0).getid(), specL.getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd "location", specL.getid(), null, "autoAddLocation"); pm.makePersistent(tSL); } // search Dept for Location where distant Members presumed not to be responding are set String queryFarawayLocs = "select from " + Location.class.getName() + " where vru == '2' && deptId == " + deptId; log.info("querySpecialLocs: " + queryFarawayLocs); List<Location> farawayLoc = (List<Location>) pm.newQuery(queryFarawayLocs).execute(); log.info("queryFarawayLocs qty: " + farawayLoc.size()); // create Tracking records for Members presumed not to be responder due to fresh ETA String queryFarAwayResponders = "select from " + Member.class.getName() + " where distGroup == '4' "; log.info("queryFarAwayResponders: " + queryFarAwayResponders); List<Member> farawayMembers = (List<Member>) pm.newQuery(queryFarAwayResponders) .execute(); log.info("queryFarAwayResponders qty: " + farawayMembers.size()); if (farawayMembers.size() != 0) { for (Member far : farawayMembers) { Tracking tMFAR = new Tracking(deptId, thisAlert.get(0).getid(), farawayLoc.get(0).getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd "farawayAddMember", far.getid(), null, responseType); pm.makePersistent(tMFAR); } } // TODO: testing restriction HACKER - remove at launch // send alert email String queryMember = "select from " + Member.class.getName() + " where deptId == " + deptId + " && type == 'Hacker' "; List<Member> members = (List<Member>) pm.newQuery(queryMember).execute(); //TODO Geocode address to insure easy navigation //TODO johnreilly: add street and town fields to Alert msg.setFrom( new InternetAddress("admin@responderiq05.appspotmail.com", "FirstResponder")); msg.setSubject("Alert!"); msg.setText(" Y=" + d.getinboundVRU1() + "&N=" + d.getinboundVRU2() + // "&3=" + d.getinboundVRU3() + "&A=" + thisAlert.get(0).getalertMsgString()); // send message to all dept members who permit tracking (and sending email alerts) for (Member m : members) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.getsmsAddress(), m.getfirstName() + "" + m.getlastName())); log.info("Member: " + m.getsmsAddress() + "|" + m.getlastName()); } } // only process for one department - should only be one department break; } } } catch (MessagingException me) { log.info("Error: Messaging"); } catch (IndexOutOfBoundsException mi) { log.info("Error: Out of Bounds"); } // Do not send alert notification if email is a Google Confirmation // if (! sender.toString().contains("mail-noreply@google.com")) { // Transport.send(msg); // } } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { pm.close(); } }
From source file:com.zxy.commons.email.MailMessageUtils.java
/** * ??eml//from w ww . j a v a 2s . co m * * @param inputStream inputStream * @param from from * @param tos tos * @param properties * @param isCloseInputStream ???InputStream * @throws EmailException EmailException * @throws MessagingException MessagingException */ @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public static void sendEml(InputStream inputStream, String from, List<String> tos, Map<String, String> properties, boolean isCloseInputStream) throws EmailException, MessagingException { try { // inputStream = new SharedFileInputStream(mailPath); Session session = getEmail().getMailSession(); // session.getProperties().setProperty("mail.smtp.ehlo", "true"); MimeMessage message = new MimeMessage(session, inputStream); if (!Strings.isNullOrEmpty(from)) { message.setFrom(new InternetAddress(from)); } // for (Map.Entry<String, String> entry : properties.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); message.setHeader(name, value); } if (tos == null || tos.isEmpty()) { Transport.send(message); } else { InternetAddress[] internetAddresses = new InternetAddress[tos.size()]; int index = 0; for (String to : tos) { internetAddresses[index] = new InternetAddress(to); index++; } Transport.send(message, internetAddresses); } } finally { if (isCloseInputStream) { IOUtils.closeQuietly(inputStream); } } }
From source file:com.adaptris.mail.ApacheMailClient.java
private MimeMessage createMimeMessage(Session session, Reader src) throws IOException, MessagingException { MimeMessage result = null;//from ww w .j a va2 s . c o m StringWriter writer = new StringWriter(); try (BufferedReader bufferedReader = new BufferedReader(src)) { IOUtils.copy(bufferedReader, writer); } try (InputStream mimeMessageInput = IOUtils.toInputStream(writer.toString(), Charset.defaultCharset())) { result = new MimeMessage(session, mimeMessageInput); } return result; }
From source file:com.spartasystems.holdmail.smtp.OutgoingMailSender.java
protected Message initializeMimeMessage(String rawBody, Session session) throws MessagingException { return new MimeMessage(session, IOUtils.toInputStream(rawBody, StandardCharsets.UTF_8)); }
From source file:com.glaf.mail.MxMailHelper.java
public Mail getMail(InputStream inputStream) { try {/*w w w.j a va2 s . com*/ Properties props = new Properties(); props.put("mail.pop3.host", "abcd.com"); Session session = Session.getInstance(props); MimeMessage mimeMessage = new MimeMessage(session, inputStream); Object body = mimeMessage.getContent(); Mail mail = new Mail(); if (body instanceof Multipart) { processMultipart((Multipart) body, mail); } else { processPart(mimeMessage, mail); } return mail; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.opensearchserver.extractor.parser.Eml.java
@Override protected void parseContent(InputStream inputStream, String extension, String mimeType) throws Exception { Session session = Session.getDefaultInstance(JAVAMAIL_PROPS); MimeMessage mimeMessage = new MimeMessage(session, inputStream); MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse(); ParserDocument document = getNewParserDocument(); String from = mimeMessageParser.getFrom(); if (from != null) document.add(FROM, from.toString()); for (Address address : mimeMessageParser.getTo()) document.add(RECIPIENT_TO, address.toString()); for (Address address : mimeMessageParser.getCc()) document.add(RECIPIENT_CC, address.toString()); for (Address address : mimeMessageParser.getBcc()) document.add(RECIPIENT_BCC, address.toString()); document.add(SUBJECT, mimeMessageParser.getSubject()); document.add(HTML_CONTENT, mimeMessageParser.getHtmlContent()); document.add(PLAIN_CONTENT, mimeMessageParser.getPlainContent()); document.add(SENT_DATE, mimeMessage.getSentDate()); document.add(RECEIVED_DATE, mimeMessage.getReceivedDate()); for (DataSource dataSource : mimeMessageParser.getAttachmentList()) { document.add(ATTACHMENT_NAME, dataSource.getName()); document.add(ATTACHMENT_TYPE, dataSource.getContentType()); // TODO Extract content from attachmend // if (parserSelector != null) { // Parser attachParser = parserSelector.parseStream( // getSourceDocument(), dataSource.getName(), // dataSource.getContentType(), null, // dataSource.getInputStream(), null, null, null); // if (attachParser != null) { // List<ParserResultItem> parserResults = attachParser // .getParserResults(); // if (parserResults != null) // for (ParserResultItem parserResult : parserResults) // result.addField( // ParserFieldEnum.email_attachment_content, // parserResult); // }/*from w w w. j a v a2 s . c o m*/ // } } if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent())) document.add(LANG_DETECTION, languageDetection(document, PLAIN_CONTENT, 10000)); else document.add(LANG_DETECTION, languageDetection(document, HTML_CONTENT, 10000)); }
From source file:com.qwazr.library.email.EmlParser.java
@Override public void parseContent(final MultivaluedMap<String, String> parameters, final InputStream inputStream, final String extension, final String mimeType, final ParserResultBuilder resultBuilder) throws Exception { final Session session = Session.getDefaultInstance(JAVAMAIL_PROPS); resultBuilder.metas().set(MIME_TYPE, findMimeType(extension, mimeType, this::findMimeTypeUsingDefault)); final MimeMessage mimeMessage = new MimeMessage(session, inputStream); final MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse(); ParserFieldsBuilder document = resultBuilder.newDocument(); final String from = mimeMessageParser.getFrom(); if (from != null) document.add(FROM, from);/* ww w.j a va2 s . c o m*/ for (Address address : mimeMessageParser.getTo()) document.add(RECIPIENT_TO, address.toString()); for (Address address : mimeMessageParser.getCc()) document.add(RECIPIENT_CC, address.toString()); for (Address address : mimeMessageParser.getBcc()) document.add(RECIPIENT_BCC, address.toString()); document.add(SUBJECT, mimeMessageParser.getSubject()); document.add(HTML_CONTENT, mimeMessageParser.getHtmlContent()); document.add(PLAIN_CONTENT, mimeMessageParser.getPlainContent()); document.add(SENT_DATE, mimeMessage.getSentDate()); document.add(RECEIVED_DATE, mimeMessage.getReceivedDate()); for (DataSource dataSource : mimeMessageParser.getAttachmentList()) { document.add(ATTACHMENT_NAME, dataSource.getName()); document.add(ATTACHMENT_TYPE, dataSource.getContentType()); // TODO Extract content from attachmend // if (parserSelector != null) { // Parser attachParser = parserSelector.parseStream( // getSourceDocument(), dataSource.getName(), // dataSource.getContentType(), null, // dataSource.getInputStream(), null, null, null); // if (attachParser != null) { // List<ParserResultItem> parserResults = attachParser // .getParserResults(); // if (parserResults != null) // for (ParserResultItem parserResult : parserResults) // result.addField( // ParserFieldEnum.email_attachment_content, // parserResult); // } // } } if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent())) document.add(LANG_DETECTION, languageDetection(document, PLAIN_CONTENT, 10000)); else document.add(LANG_DETECTION, languageDetection(document, HTML_CONTENT, 10000)); }
From source file:com.spartasystems.holdmail.util.TestMailClient.java
public void sendResourceEmail(String resourceName, String sender, String recipient, String subject) { try {//from w w w.j av a 2s . c o m InputStream resource = TestMailClient.class.getClassLoader().getResourceAsStream(resourceName); if (resource == null) { throw new MessagingException("Couldn't find resource at: " + resourceName); } Message message = new MimeMessage(session, resource); // wipe out ALL exisitng recipients message.setRecipients(Message.RecipientType.TO, new Address[] {}); message.setRecipients(Message.RecipientType.CC, new Address[] {}); message.setRecipients(Message.RecipientType.BCC, new Address[] {}); // then set the new data message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); message.setFrom(InternetAddress.parse(sender)[0]); message.setSubject(subject); Transport.send(message); logger.info("Outgoing mail forwarded to " + recipient); } catch (MessagingException e) { throw new HoldMailException("couldn't send mail: " + e.getMessage(), e); } }
From source file:com.liusoft.dlog4j.MailTransportQueue.java
/** * ??//from w w w. j a v a2s .c o m * @param mails ?,? * @param ident ?, * @param max_count * @return * @throws IOException */ public int read(Session ssn, List mails, List ident, int max_count) throws IOException { File fs = new File(path); File[] mailfiles = fs.listFiles(new FileFilter() { public boolean accept(File f) { if (f.length() > 0 && f.getName().endsWith(EML)) return true; return false; } }); if (mails != null) { for (int i = 0; i < mailfiles.length && i < max_count; i++) { FileInputStream fis = null; try { fis = new FileInputStream(mailfiles[i]); mails.add(new MimeMessage(ssn, fis)); if (ident != null) ident.add(mailfiles[i].getPath()); fis.close(); fis = null; mailfiles[i].delete(); } catch (MessagingException e) { String newfile = mailfiles[i].getPath() + ERR; mailfiles[i].renameTo(new File(newfile)); log.error("mail cache file destroy, rename to " + newfile, e); } catch (IOException e) { String newfile = mailfiles[i].getPath() + ERR; mailfiles[i].renameTo(new File(newfile)); log.error("IO Exception when read mail cache , rename to " + newfile, e); } finally { if (fis != null) fis.close(); } } } return mailfiles.length; }