public JSONObject toJSON() { JSONObject jo = new JSONObject(); if (from != null) { jo.put("from", InternetAddress.toString(new InternetAddress[] {from})); } if (subject != null) { jo.put("subject", this.subject); } if (text != null) { jo.put("text", this.text); } if (tos != null) { jo.put("tos", InternetAddress.toString(tos)); } if (ccs != null) { jo.put("ccs", InternetAddress.toString(ccs)); } if (bccs != null) { jo.put("bccs", InternetAddress.toString(bccs)); } // if(files!=null) jo.put("form", $file.toSting(files)); if (error != null) { jo.put("error", error); } if (name != null) { jo.put("name", name); } return jo; }
@Override public String marshal(InternetAddress v) throws Exception { if (v == null) { return ""; } else { return v.toString(); } }
public void publish0( final RfQResponsePublisherRequest request, final RfQReportType rfqReportType) { final I_C_RfQResponse rfqResponse = request.getC_RfQResponse(); // // Check and get the user's mail where we will send the email to final I_AD_User userTo = rfqResponse.getAD_User(); if (userTo == null) { throw new RfQPublishException(request, "@NotFound@ @AD_User_ID@"); } final String userToEmail = userTo.getEMail(); if (Check.isEmpty(userToEmail, true)) { throw new RfQPublishException(request, "@NotFound@ @AD_User_ID@ @Email@ - " + userTo); } // final IMailTextBuilder mailTextBuilder = createMailTextBuilder(rfqResponse, rfqReportType); // final String subject = mailTextBuilder.getMailHeader(); final String message = mailTextBuilder.getFullMailText(); final DefaultModelArchiver archiver = DefaultModelArchiver.of(rfqResponse) .setAD_PrintFormat_ID(getAD_PrintFormat_ID(rfqResponse, rfqReportType)); final I_AD_Archive pdfArchive = archiver.archive(); final byte[] pdfData = archiver.getPdfData(); // // Send it final EMail email = mailBL.createEMail( rfqResponse.getAD_Client() // , (String) null // mailCustomType , (I_AD_User) null // from , userToEmail // to , subject, message, mailTextBuilder.isHtml() // html ); email.addAttachment("RfQ_" + rfqResponse.getC_RfQResponse_ID() + ".pdf", pdfData); final EMailSentStatus emailSentStatus = email.send(); // // Fire mail sent/not sent event (even if there were some errors) { final InternetAddress from = email.getFrom(); final String fromStr = from == null ? null : from.toString(); final InternetAddress to = email.getTo(); final String toStr = to == null ? null : to.getAddress(); archiveEventManager.fireEmailSent( pdfArchive // archive , X_C_Doc_Outbound_Log_Line.ACTION_EMail // action , (I_AD_User) null // user , fromStr // from , toStr // to , (String) null // cc , (String) null // bcc , emailSentStatus.getSentMsg() // status ); } // // Update RfQ response (if success) if (emailSentStatus.isSentOK()) { rfqResponse.setDateInvited(new Timestamp(System.currentTimeMillis())); InterfaceWrapperHelper.save(rfqResponse); } else { throw new RfQPublishException(request, emailSentStatus.getSentMsg()); } }
/** * Send <strong><em>one</em></strong> mail to multiple recipients and multiple BCC recipients * <em>(in one mail)</em>. * * @param transport transport connection, if null transport is create inside the method * @param sender the "From" field * @param recipients the "To" field with multiple addresses. * @param bccRecipients the "Bcc" field with multiple addresses. * @param subject the Subject of the message * @param content the Content of the message * @param isHTML flag indicating wether the Content is html (<code>true</code>) or text (<code> * false</code>) * @throws MessagingException Forwarded exception from javax.mail * @throws IllegalArgumentException if no recipient provided or no sender */ public void sendMail( Transport transport, InternetAddress sender, List<InternetAddress> recipients, List<InternetAddress> ccRecipients, List<InternetAddress> bccRecipients, String subject, String content, String txtContent, boolean isHTML, Collection<Attachment> attachments) throws MessagingException { String recipientsStr = new LinkedList<InternetAddress>(recipients).toString(); if (sender == null || recipients == null || recipients.size() == 0) { throw new IllegalArgumentException( "Sender null (sender: " + sender + ") or no recipient: " + recipients); } if (props != null) { logger.info( "Sending mail with subject: " + subject + " to: " + recipients.size() + " recipients: " + recipientsStr + "\n" + "Using smtp: " + props.getProperty(SMTP_HOST_PARAM, DEFAULT_SMTP_HOST) + " / " + props.getProperty(SMTP_USER_PARAM) + " / " + props.getProperty(SMTP_PASSWORD_PARAM)); } Date sendDate = new Date(); if (!DEBUG) { Session mailSession = Session.getDefaultInstance(props); MimeMessage msg = new MimeMessage(mailSession); msg.setSentDate(sendDate); msg.setFrom(sender); msg.setRecipients( Message.RecipientType.TO, recipients.toArray(new InternetAddress[recipients.size()])); if (ccRecipients != null && ccRecipients.size() > 0) { msg.setRecipients( Message.RecipientType.CC, ccRecipients.toArray(new InternetAddress[ccRecipients.size()])); } if (bccRecipients != null && bccRecipients.size() > 0) { msg.setRecipients( Message.RecipientType.BCC, bccRecipients.toArray(new InternetAddress[bccRecipients.size()])); } msg.setSubject(subject, ContentContext.CHARACTER_ENCODING); if (isHTML) { MimeBodyPart wrap = new MimeBodyPart(); MimeMultipart cover = new MimeMultipart("alternative"); MimeBodyPart bp = new MimeBodyPart(); if (txtContent == null) { txtContent = StringHelper.html2txt(content); } bp.setText(txtContent, ContentContext.CHARACTER_ENCODING); cover.addBodyPart(bp); bp = new MimeBodyPart(); bp.setText(content, ContentContext.CHARACTER_ENCODING, "html"); cover.addBodyPart(bp); wrap.setContent(cover); MimeMultipart contentMail = new MimeMultipart("related"); if (attachments != null) { for (Attachment attach : attachments) { String id = UUID.randomUUID().toString(); /* * sb.append("<img src=\"cid:"); sb.append(id); * sb.append("\" alt=\"ATTACHMENT\"/>\n"); */ MimeBodyPart attachment = new MimeBodyPart(); DataSource fds = new ByteArrayDataSource( attach.getData(), ResourceHelper.getFileExtensionToMineType( StringHelper.getFileExtension(attach.getName()))); attachment.setDataHandler(new DataHandler(fds)); attachment.setHeader("Content-ID", "<" + id + ">"); attachment.setFileName(attach.getName()); contentMail.addBodyPart(attachment); } } contentMail.addBodyPart(wrap); msg.setContent(contentMail); msg.setSentDate(new Date()); } else { assert attachments == null : "no attachements in text format."; msg.setText(content); } /* * if (isHTML) { msg.addHeader("Content-Type", * "text/html; charset=\"" + ContentContext.CHARACTER_ENCODING + * "\""); } */ msg.saveChanges(); if (transport == null || !transport.isConnected()) { transport = getMailTransport(staticConfig); try { transport.sendMessage(msg, msg.getAllRecipients()); } finally { transport.close(); } } else { transport.sendMessage(msg, msg.getAllRecipients()); } } else { FileOutputStream out = null; try { PrintStream w = System.out; if (tempDir != null && new File(tempDir).exists()) { File mailFile = new File( tempDir, "mail-debug/mail-" + StringHelper.renderFileTime(sendDate) + "-" + StringHelper.stringToFileName(subject) + ".txt"); mailFile.getParentFile().mkdirs(); out = new FileOutputStream(mailFile, true); w = new PrintStream(mailFile, ContentContext.CHARACTER_ENCODING); } else { w.println(""); } w.println("FROM:"); w.println(sender.toString()); w.print("TO: #"); w.println(Integer.toString(recipients.size())); for (InternetAddress recipient : recipients) { w.println(recipient.toString()); } if (ccRecipients != null) { w.print("CC: #"); w.println(Integer.toString(ccRecipients.size())); for (InternetAddress ccRecipient : ccRecipients) { w.println(ccRecipient.toString()); } } if (bccRecipients != null) { w.print("BCC: #"); w.println(Integer.toString(bccRecipients.size())); for (InternetAddress bccRecipient : bccRecipients) { w.println(bccRecipient.toString()); } } w.println("SUBJECT:"); w.println(subject); w.print("IS HTML: "); w.println(isHTML); w.println("CONTENT:"); w.print("--BEGIN--"); w.print(content); w.println("--END--"); w.println(""); w.flush(); } catch (IOException e) { throw new RuntimeException("Exception when writing debug mail file.", e); } finally { ResourceHelper.safeClose(out); } } logger.info("Mail sent to: " + recipientsStr); }
/** * Receive Email from POPServer. Use POP3 protocal by default. Thus, call this method, you need to * provide a pop3 mail server address. * * @param emailAddress The email account in the POPServer. * @param password The password of email address. */ public static void receiveEmail(String host, String username, String password) { // param check. If param is null, use the default configured value. if (host == null) { host = POP3Server; } if (username == null) { username = POP3Username; } if (password == null) { password = POP3Password; } Properties props = System.getProperties(); // MailAuthenticator authenticator = new MailAuthenticator(username, password); try { Session session = Session.getDefaultInstance(props, null); // Store store = session.getStore("imap"); Store store = session.getStore("pop3"); // Connect POPServer store.connect(host, username, password); Folder inbox = store.getFolder("INBOX"); if (inbox == null) { throw new RuntimeException("No inbox existed."); } // Open the INBOX with READ_ONLY mode and start to read all emails. inbox.open(Folder.READ_ONLY); System.out.println("TOTAL EMAIL:" + inbox.getMessageCount()); Message[] messages = inbox.getMessages(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; String from = InternetAddress.toString(msg.getFrom()); String replyTo = InternetAddress.toString(msg.getReplyTo()); String to = InternetAddress.toString(msg.getRecipients(Message.RecipientType.TO)); String subject = msg.getSubject(); Date sent = msg.getSentDate(); Date ress = msg.getReceivedDate(); String type = msg.getContentType(); System.out.println((i + 1) + ".---------------------------------------------"); System.out.println("From:" + mimeDecodeString(from)); System.out.println("Reply To:" + mimeDecodeString(replyTo)); System.out.println("To:" + mimeDecodeString(to)); System.out.println("Subject:" + mimeDecodeString(subject)); System.out.println("Content-type:" + type); if (sent != null) { System.out.println("Sent Date:" + sdf.format(sent)); } if (ress != null) { System.out.println("Receive Date:" + sdf.format(ress)); } // //Get message headers. // @SuppressWarnings("rawtypes") // Enumeration headers = msg.getAllHeaders(); // while (headers.hasMoreElements()) { // Header h = (Header) headers.nextElement(); // String name = h.getName(); // String val = h.getValue(); // System.out.println(name + ": " + val); // } // //get the email content. // Object content = msg.getContent(); // System.out.println(content); // //print content // Reader reader = new InputStreamReader( // messages[i].getInputStream()); // int a = 0; // while ((a = reader.read()) != -1) { // System.out.print((char) a); // } } // close connection. param false represents do not delete messaegs on server. inbox.close(false); store.close(); // } catch(IOException e) { // LOGGER.error("IOException caught while printing the email content", e); } catch (MessagingException e) { LOGGER.error("MessagingException caught when use message object", e); } }