List of usage examples for javax.mail.internet MimeMessage writeTo
@Override public void writeTo(OutputStream os) throws IOException, MessagingException
From source file:org.jresponder.webapi.AdminApiController.java
/** * REST-style call to preview a message in the context of a particular * subscriber and subscription (specified by message group name). * <p>// w w w .j a v a 2 s. com * Example request: /admin/api/message-preview.action?email=test@example.com&message_group_name=list1&message_name=example1 * * @param aId * @param aParams * @return * @throws MessagingException * @throws IOException */ @RequestMapping("message-preview") public ResponseEntity<String> subscribe(@RequestParam("email") String aEmail, @RequestParam("message_group_name") String aMessageGroupName, @RequestParam("message_name") String aMessageName) throws Exception { Subscriber mySubscriber = subscriberService.lookupSubscriber(aEmail); if (mySubscriber == null) return webApiUtil.result404("Couldn't find subscriber"); Subscription mySubscription = null; for (Subscription myTempSubscription : mySubscriber.getSubscriptions()) { if (myTempSubscription.getMessageGroupName().equals(aMessageGroupName)) { mySubscription = myTempSubscription; } } if (mySubscription == null) return webApiUtil.result404("Couldn't find subscription"); MessageGroup myMessageGroup = messageGroupSource.getMessageGroupByName(aMessageGroupName); if (myMessageGroup == null) return webApiUtil.result404("Couldn't find message group"); MessageRef myMessageRef = myMessageGroup.getMessageRefByName(aMessageName); MimeMessage myMimeMessage = javaMailSender.createMimeMessage(); SendConfig mySendConfig = sendConfigGroup.lookupSendConfig(mySubscriber, mySubscription, myMessageGroup, myMessageRef); if (mySendConfig == null) { throw new IllegalStateException("No SendConfig for this message, cannot continue!"); } myMessageRef.populateMessage(myMimeMessage, mySendConfig, mySubscriber, mySubscription); ByteArrayOutputStream myByteArrayOutputStream = new ByteArrayOutputStream(); myMimeMessage.writeTo(myByteArrayOutputStream); return webApiUtil.plainTextResult(myByteArrayOutputStream.toString("UTF-8")); }
From source file:com.niroshpg.android.gmail.CronHandlerServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Check if we have stored credentials using the Authorization Flow. // Note that we only check if there are stored credentials, but not if they are still valid. // The user may have revoked authorization, in which case we would need to go through the // authorization flow again, which this implementation does not handle. GoogleAuthorizationCodeFlow authFlow = GmailUtils.newFlow(); Credential credential = null;// w w w .j a va 2s .c o m String userId = Datastore.getUserId(); credential = authFlow.loadCredential(userId); if (credential == null) { // // If we don't have a token in store, redirect to authorization screen. logger.warning("auth flow started ..."); resp.sendRedirect( authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build()); return; } // Create a new authorized Gmail API client Gmail service = new Gmail.Builder(GmailUtils.HTTP_TRANSPORT, GmailUtils.JSON_FACTORY, credential) .setApplicationName(APP_NAME).build(); List<Label> lableList = listLabels(service, "me"); List<Message> messegeList = listMessagesWithLabels(service, "me", Arrays.asList(getLableIdForName(lableList, "EQM"))); logger.warning("store messages for processing ... "); for (Message message : messegeList) { String messageBody = ""; try { MimeMessage mimeMessage = getMimeMessage(service, "me", message.getId()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); messageBody = baos.toString(); } catch (MessagingException e) { e.printStackTrace(); } String extractedMsgBody = MessageUtility.extractData(messageBody); Datastore.addMessage(extractedMsgBody); } logger.warning("invoke send all"); sendMessagesToAll(); logger.warning("removing label from messages ..."); removeUnRead(service, "me", messegeList); }
From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java
private void logEmail(MultiPartEmail multiPartMessage) { if (multiPartMessage != null) { MimeMessage mimeMessage = multiPartMessage.getMimeMessage(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {/* w ww . j a v a 2 s .c o m*/ mimeMessage.writeTo(new FilterOutputStream(baos)); LOGGER.debug("Email content = \n" + baos.toString()); } catch (IOException e) { LOGGER.error("failed to log email", e); } catch (MessagingException e) { LOGGER.error("failed to log email", e); } } else { LOGGER.error("Email is null"); } }
From source file:org.apache.axis.transport.mail.MailWorker.java
/** * Send the soap request message to the server * // w w w .j a v a 2 s .c o m * @param msgContext * @param smtpHost * @param sendFrom * @param replyTo * @param output * @throws Exception */ private void writeUsingSMTP(MessageContext msgContext, String smtpHost, String sendFrom, String replyTo, String subject, Message output) throws Exception { SMTPClient client = new SMTPClient(); client.connect(smtpHost); // After connection attempt, you should check the reply code to verify // success. System.out.print(client.getReplyString()); int reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } client.login(smtpHost); System.out.print(client.getReplyString()); reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(sendFrom)); msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(replyTo)); msg.setDisposition(MimePart.INLINE); msg.setSubject(subject); ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024); output.writeTo(out); msg.setContent(out.toString(), output.getContentType(msgContext.getSOAPConstants())); ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024); msg.writeTo(out2); client.setSender(sendFrom); System.out.print(client.getReplyString()); client.addRecipient(replyTo); System.out.print(client.getReplyString()); Writer writer = client.sendMessageData(); System.out.print(client.getReplyString()); writer.write(out2.toString()); writer.flush(); writer.close(); System.out.print(client.getReplyString()); if (!client.completePendingCommand()) { System.out.print(client.getReplyString()); AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null); throw fault; } System.out.print(client.getReplyString()); client.logout(); client.disconnect(); }
From source file:com.liusoft.dlog4j.MailTransportQueue.java
/** * ?/* w w w.ja v a2 s .c o m*/ * @param sid * @param mail * @return ??() * @throws IOException * @throws MessagingException */ public String write(int sid, MimeMessage mail) throws IOException, MessagingException { int tryCount = 0; do { StringBuffer fn = new StringBuffer(path); fn.append(System.currentTimeMillis()); fn.append('_'); fn.append(sid); fn.append(EML); File f = new File(fn.toString()); if (f.exists()) { tryCount++; try { Thread.sleep(10); } catch (InterruptedException e) { break; } } else if (f.createNewFile()) { FileOutputStream fos = new FileOutputStream(f); try { mail.writeTo(fos); return f.getPath(); } finally { fos.close(); } } break; } while (tryCount < 10); return null; }
From source file:MSMessage.java
/** * Constructor that converts a MimeMessage object into a MSMessage. * /*from ww w . ja v a 2 s. co m*/ * @exception MessagingException if the given MimeMessage * is not a non-MIME MS message, or if an * IOException occurs when accessing the given * MimeMessage object */ public MSMessage(Session session, MimeMessage msg) throws MessagingException { super(session); if (!isMSMessage(msg)) // sanity check throw new MessagingException("Not an MS message"); class FastByteArrayOutputStream extends ByteArrayOutputStream { ByteArrayInputStream toByteArrayInputStream() { return new ByteArrayInputStream(buf, 0, count); } } // extract the bytes of the given message // ByteArrayOutputStream bos = new ByteArrayOutputStream(); FastByteArrayOutputStream bos = new FastByteArrayOutputStream(); try { msg.writeTo(bos); } catch (IOException ioex) { throw new MessagingException("IOException", ioex); } catch (Exception ex) { throw new MessagingException("Exception", ex); } //parse(new ByteArrayInputStream(bos.toByteArray())); parse(bos.toByteArrayInputStream()); }
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
private EmailMessage wrapMessage(Message msg, boolean populateContent, Session session) throws MessagingException, IOException, ScanException, PolicyException { // Prepare subject String subject = msg.getSubject(); if (!StringUtils.isBlank(subject)) { AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(subject, policy); subject = cr.getCleanHTML();/*w ww . java 2 s .c o m*/ } // Prepare content if requested EmailMessageContent msgContent = null; // default... if (populateContent) { // Defend against the dreaded: "Unable to load BODYSTRUCTURE" try { msgContent = getMessageContent(msg.getContent(), msg.getContentType()); } catch (MessagingException me) { // We are unable to read digitally-signed messages (perhaps // others?) in the API-standard way; we have to use a work around. // See: http://www.oracle.com/technetwork/java/faq-135477.html#imapserverbug // Logging as DEBUG because this behavior is known & expected. log.debug("Difficulty reading a message (digitally signed?). Attempting workaround..."); try { MimeMessage mm = (MimeMessage) msg; ByteArrayOutputStream bos = new ByteArrayOutputStream(); mm.writeTo(bos); bos.close(); SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray()); MimeMessage copy = new MimeMessage(session, bis); bis.close(); msgContent = getMessageContent(copy.getContent(), copy.getContentType()); } catch (Throwable t) { log.error("Failed to read message body", t); msgContent = new EmailMessageContent("UNABLE TO READ MESSAGE BODY: " + t.getMessage(), false); } } // Sanitize with AntiSamy String content = msgContent.getContentString(); if (!StringUtils.isBlank(content)) { AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(content, policy); content = cr.getCleanHTML(); } msgContent.setContentString(content); } int messageNumber = msg.getMessageNumber(); // Prepare the UID if present String uid = null; // default if (msg.getFolder() instanceof UIDFolder) { uid = Long.toString(((UIDFolder) msg.getFolder()).getUID(msg)); } Address[] addr = msg.getFrom(); String sender = getFormattedAddresses(addr); Date sentDate = msg.getSentDate(); boolean unread = !msg.isSet(Flag.SEEN); boolean answered = msg.isSet(Flag.ANSWERED); boolean deleted = msg.isSet(Flag.DELETED); // Defend against the dreaded: "Unable to load BODYSTRUCTURE" boolean multipart = false; // sensible default; String contentType = null; // sensible default try { multipart = msg.getContentType().toLowerCase().startsWith(CONTENT_TYPE_ATTACHMENTS_PATTERN); contentType = msg.getContentType(); } catch (MessagingException me) { // Message was digitally signed and we are unable to read it; // logging as DEBUG because this issue is known/expected, and // because the user's experience is in no way affected (at this point) log.debug("Message content unavailable (digitally signed?); " + "message will appear in the preview table correctly, " + "but the body will not be viewable"); log.trace(me.getMessage(), me); } String to = getTo(msg); String cc = getCc(msg); String bcc = getBcc(msg); return new EmailMessage(messageNumber, uid, sender, subject, sentDate, unread, answered, deleted, multipart, contentType, msgContent, to, cc, bcc); }
From source file:org.apache.james.mailrepository.file.MBoxMailRepository.java
/** * Convert a MimeMessage into raw text//from w ww . j a v a 2 s.c o m * * @param mc * The mime message to convert * @return A string representation of the mime message * @throws IOException * @throws MessagingException */ private String getRawMessage(MimeMessage mc) throws IOException, MessagingException { ByteArrayOutputStream rawMessage = new ByteArrayOutputStream(); mc.writeTo(rawMessage); return rawMessage.toString(); }
From source file:com.niroshpg.android.gmail.PlusSampleServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Check if we have stored credentials using the Authorization Flow. // Note that we only check if there are stored credentials, but not if they are still valid. // The user may have revoked authorization, in which case we would need to go through the // authorization flow again, which this implementation does not handle. GoogleAuthorizationCodeFlow authFlow = GmailUtils.newFlow(); UserService userService = UserServiceFactory.getUserService(); Credential credential = null;// w ww . j ava 2 s.c o m if (userService != null) { String userId = userService.getCurrentUser().getUserId(); Datastore.saveUserId(userId); credential = authFlow.loadCredential(userId); // if (credential == null) { // // If we don't have a token in store, redirect to authorization screen. logger.warning("auth flow started ..."); resp.sendRedirect( authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build()); return; } // try{ // credential.refreshToken(); // } // catch(TokenResponseException e){ // resp.sendRedirect( // authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build()); // return; // } // Create a new authorized Gmail API client Gmail service = new Gmail.Builder(GmailUtils.HTTP_TRANSPORT, GmailUtils.JSON_FACTORY, credential) .setApplicationName(APP_NAME).build(); // Make the API call BigInteger startHistoryId = null; //service.users().getProfile("me").setRequestHeaders(service.users().getProfile("me").getRequestHeaders().) startHistoryId = getHistoryId(service, "me", credential); logger.warning("hid[url]= " + startHistoryId); List<Label> lableList = listLabels(service, "me"); List<Message> messegeList = listMessagesWithLabels(service, "me", Arrays.asList(getLableIdForName(lableList, "EQM")/*, getLableIdForName(lableList,"UNREAD")*/ )); logger.warning("store messages for processing ... "); for (Message message : messegeList) { //Message detailMessage = getMessage(service, "me", message.getId()); String messageBody = ""; try { MimeMessage mimeMessage = getMimeMessage(service, "me", message.getId()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); messageBody = baos.toString(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } //logger.warning("working "+detailMessage.getSnippet()+" ... "); //logger.warning("messageBody= "+messageBody+" ... "); //String messageBody = StringUtils.newStringUtf8(Base64.decodeBase64(detailMessage.getRaw()));//StringUtils.newStringUtf8(detailMessage.getPayload().getBody().decodeData()/*Base64.decodeBase64(detailMessage.getPayload().getBody().decodeData())*/); //String messageBody = StringUtils.newStringUtf8(detailMessage.getPayload().getBody().decodeData()); String extractedMsgBody = MessageUtility.extractData(messageBody); //logger.warning("adding "+extractedMsgBody+" ... "); Datastore.addMessage(extractedMsgBody); } logger.warning("invoke send all"); sendMessagesToAll(); logger.warning("removing label from messages ..."); removeUnRead(service, "me", messegeList); //List<History> historyList = null; //if(messegeList != null && messegeList.size() > 1) //{ // logger.warning("messege count = " + messegeList.size()); // // for(Message amsg : messegeList) // { //logger.warning("id= " + amsg.getId()); // if(amsg.getHistoryId() != null) // { // startHistoryId = amsg.getHistoryId(); //logger.warning("hid= " + amsg.getHistoryId()); // break; // } //} // if(startHistoryId != null) // { // historyList = listHistory(service, "me", startHistoryId); // } // else // { // logger.warning("could not find start history id"); // // //historyList = listHistory(service, "me", BigInteger.valueOf(1)); // // } // } resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); PrintWriter writer = resp.getWriter(); writer.println("<!doctype html><html><head>"); writer.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"); writer.println("<title>" + APP_NAME + "</title>"); writer.println("</head><body>"); //printThreadIds(service,writer); if (messegeList != null && messegeList.size() > 0) { writer.println("<p> msg count = " + messegeList.size() + "</p>"); //for(Message msg : messegeList){ //writer.println("<p>"+msg.toPrettyString()+"</p>"); //} } // if(historyList != null && historyList.size() >0) // { // for(History history : historyList){ // writer.println("<p>"+history.toPrettyString()+"</p>"); // } // } else { writer.println("<p>history not found</p>"); } writer.println("<div class=\"header\"><b>" + req.getUserPrincipal().getName() + "</b> | " + "<a href=\"" + userService.createLogoutURL(req.getRequestURL().toString()) + "\">Log out</a> | " + "<a href=\"http://code.google.com/p/google-api-java-client/source/browse" + "/calendar-appengine-sample?repo=samples\">See source code for " + "this sample</a></div>"); writer.println("<div id=\"main\"/>"); writer.println("</body></html>"); } else { PrintWriter writer = resp.getWriter(); writer.println("<!doctype html><html><head>"); writer.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"); writer.println("<title>" + APP_NAME + "</title>"); writer.println("</head><body>"); writer.println("<h2>user service not found</h2>"); writer.println("</body></html>"); } }
From source file:org.apache.james.spamassassin.SpamAssassinInvoker.java
public SpamAssassinResult scanMailWithAdditionalHeaders(MimeMessage message, String... additionalHeaders) throws MessagingException { try (Socket socket = new Socket(spamdHost, spamdPort); OutputStream out = socket.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out); PrintWriter writer = new PrintWriter(bufferedOutputStream); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { writer.write("CHECK SPAMC/1.2"); writer.write(CRLF);/*from w w w . ja v a 2s . c om*/ Arrays.stream(additionalHeaders).forEach(header -> { writer.write(header); writer.write(CRLF); }); writer.write(CRLF); writer.flush(); // pass the message to spamd message.writeTo(out); out.flush(); socket.shutdownOutput(); return in.lines().filter(this::isSpam).map(this::processSpam).findFirst() .orElse(SpamAssassinResult.empty()); } catch (UnknownHostException e) { throw new MessagingException("Error communicating with spamd. Unknown host: " + spamdHost); } catch (IOException | MessagingException e) { throw new MessagingException("Error communicating with spamd on " + spamdHost + ":" + spamdPort, e); } }