List of usage examples for javax.mail.internet MimeMessage setSentDate
@Override public void setSentDate(Date d) throws MessagingException
From source file:davmail.exchange.ews.EwsExchangeSession.java
/** * Get item content.// w w w.j a v a 2s. c om * * @param itemId EWS item id * @return item content as byte array * @throws IOException on error */ protected byte[] getContent(ItemId itemId) throws IOException { GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true); byte[] mimeContent = null; try { executeMethod(getItemMethod); mimeContent = getItemMethod.getMimeContent(); } catch (EWSException e) { LOGGER.warn("GetItem with MimeContent failed: " + e.getMessage()); } if (getItemMethod.getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new HttpNotFoundException("Item " + itemId + " not found"); } if (mimeContent == null) { LOGGER.warn("MimeContent not available, trying to rebuild from properties"); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false); getItemMethod.addAdditionalProperty(Field.get("contentclass")); getItemMethod.addAdditionalProperty(Field.get("message-id")); getItemMethod.addAdditionalProperty(Field.get("from")); getItemMethod.addAdditionalProperty(Field.get("to")); getItemMethod.addAdditionalProperty(Field.get("cc")); getItemMethod.addAdditionalProperty(Field.get("subject")); getItemMethod.addAdditionalProperty(Field.get("date")); getItemMethod.addAdditionalProperty(Field.get("body")); executeMethod(getItemMethod); EWSMethod.Item item = getItemMethod.getResponseItem(); MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("Content-class", item.get(Field.get("contentclass").getResponseName())); mimeMessage.setSentDate(parseDateFromExchange(item.get(Field.get("date").getResponseName()))); mimeMessage.addHeader("From", item.get(Field.get("from").getResponseName())); mimeMessage.addHeader("To", item.get(Field.get("to").getResponseName())); mimeMessage.addHeader("Cc", item.get(Field.get("cc").getResponseName())); mimeMessage.setSubject(item.get(Field.get("subject").getResponseName())); String propertyValue = item.get(Field.get("body").getResponseName()); if (propertyValue == null) { propertyValue = ""; } mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8"); mimeMessage.writeTo(baos); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray())); } mimeContent = baos.toByteArray(); } catch (IOException e2) { LOGGER.warn(e2); } catch (MessagingException e2) { LOGGER.warn(e2); } if (mimeContent == null) { throw new IOException("GetItem returned null MimeContent"); } } return mimeContent; }
From source file:org.sakaiproject.email.impl.BasicEmailService.java
public void sendMailMessagingException(InternetAddress from, InternetAddress[] to, String subject, String content, Map<RecipientType, InternetAddress[]> headerTo, InternetAddress[] replyTo, List<String> additionalHeaders, List<Attachment> attachments) throws MessagingException { // some timing for debug long start = 0; if (M_log.isDebugEnabled()) start = System.currentTimeMillis(); // if in test mode, use the test method if (m_testMode) { testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders); return;/* w ww.j a v a 2s. c o m*/ } if (m_smtp == null) { M_log.error( "Unable to send mail as no smtp server is defined. Please set smtp@org.sakaiproject.email.api.EmailService value in sakai.properties"); return; } if (from == null) { M_log.warn("sendMail: null from"); return; } if (to == null) { M_log.warn("sendMail: null to"); return; } if (content == null) { M_log.warn("sendMail: null content"); return; } Properties props = createMailSessionProperties(); Session session = Session.getInstance(props); // see if we have a message-id in the additional headers String mid = null; if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": ")) { // length of 'message-id: ' == 12 mid = header.substring(12); break; } } } // use the special extension that can set the id MimeMessage msg = new MyMessage(session, mid); // the FULL content-type header, for example: // Content-Type: text/plain; charset=windows-1252; format=flowed String contentTypeHeader = null; // If we need to force the container to use a certain multipart subtype // e.g. 'alternative' // then sneak it through in the additionalHeaders String multipartSubtype = null; // set the additional headers on the message // but treat Content-Type specially as we need to check the charset // and we already dealt with the message id if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith(EmailHeaders.CONTENT_TYPE.toLowerCase() + ": ")) contentTypeHeader = header; else if (header.toLowerCase().startsWith(EmailHeaders.MULTIPART_SUBTYPE.toLowerCase() + ": ")) multipartSubtype = header.substring(header.indexOf(":") + 1).trim(); else if (!header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": ")) msg.addHeaderLine(header); } } // date if (msg.getHeader(EmailHeaders.DATE) == null) msg.setSentDate(new Date(System.currentTimeMillis())); // set the message sender msg.setFrom(from); // set the message recipients (headers) setRecipients(headerTo, msg); // set the reply to if ((replyTo != null) && (msg.getHeader(EmailHeaders.REPLY_TO) == null)) msg.setReplyTo(replyTo); // update to be Postmaster if necessary checkFrom(msg); // figure out what charset encoding to use // // first try to use the charset from the forwarded // Content-Type header (if there is one). // // if that charset doesn't work, try a couple others. // the character set, for example, windows-1252 or UTF-8 String charset = extractCharset(contentTypeHeader); if (charset != null && canUseCharset(content, charset) && canUseCharset(subject, charset)) { // use the charset from the Content-Type header } else if (canUseCharset(content, CharacterSet.ISO_8859_1) && canUseCharset(subject, CharacterSet.ISO_8859_1)) { if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.ISO_8859_1); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.ISO_8859_1; charset = CharacterSet.ISO_8859_1; } else if (canUseCharset(content, CharacterSet.WINDOWS_1252) && canUseCharset(subject, CharacterSet.WINDOWS_1252)) { if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.WINDOWS_1252); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.WINDOWS_1252; charset = CharacterSet.WINDOWS_1252; } else { // catch-all - UTF-8 should be able to handle anything if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.UTF_8); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.UTF_8; else contentTypeHeader = EmailHeaders.CONTENT_TYPE + ": " + ContentType.TEXT_PLAIN + "; charset=" + CharacterSet.UTF_8; charset = CharacterSet.UTF_8; } if ((subject != null) && (msg.getHeader(EmailHeaders.SUBJECT) == null)) msg.setSubject(subject, charset); // extract just the content type value from the header String contentType = null; if (contentTypeHeader != null) { int colonPos = contentTypeHeader.indexOf(":"); contentType = contentTypeHeader.substring(colonPos + 1).trim(); } setContent(content, attachments, msg, contentType, charset, multipartSubtype); // if we have a full Content-Type header, set it NOW // (after setting the body of the message so that format=flowed is preserved) // if there attachments, the messsage type will default to multipart/mixed and should // stay that way. if ((attachments == null || attachments.size() == 0) && contentTypeHeader != null) { msg.addHeaderLine(contentTypeHeader); msg.addHeaderLine(EmailHeaders.CONTENT_TRANSFER_ENCODING + ": quoted-printable"); } if (M_log.isDebugEnabled()) { M_log.debug("HeaderLines received were: "); Enumeration<String> allHeaders = msg.getAllHeaderLines(); while (allHeaders.hasMoreElements()) { M_log.debug((String) allHeaders.nextElement()); } } sendMessageAndLog(from, to, subject, headerTo, start, msg, session); }
From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java
@Override public void sendNotification(String smtpSender, String replyTo, String recipient, String subject, String htmlContent, String inReplyTo, String references) throws SendFailedException { if (smtpServer.equals("")) { logger.warn("Mail notifications are disabled."); return;/*from w w w. j av a 2 s. c o m*/ } // get the mail session Session session = getMailSession(); // Define message MimeMessage messageMim = new MimeMessage(session); try { messageMim.setFrom(new InternetAddress(smtpSender)); if (replyTo != null) { InternetAddress reply[] = new InternetAddress[1]; reply[0] = new InternetAddress(replyTo); messageMim.setReplyTo(reply); } messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); if (inReplyTo != null && inReplyTo != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(inReplyTo)) { messageMim.setHeader("In-Reply-To", inReplyTo); } } if (references != null && references != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(references)) { messageMim.setHeader("References", references); } } messageMim.setSubject(subject, charset); // Create a "related" Multipart message // content type is multipart/alternative // it will contain two part BodyPart 1 and 2 Multipart mp = new MimeMultipart("alternative"); // BodyPart 2 // content type is multipart/related // A multipart/related is used to indicate that message parts should // not be considered individually but rather // as parts of an aggregate whole. The message consists of a root // part (by default, the first) which reference other parts inline, // which may in turn reference other parts. Multipart html_mp = new MimeMultipart("related"); // Include an HTML message with images. // BodyParts: the HTML file and an image // Get the HTML file BodyPart rel_bph = new MimeBodyPart(); rel_bph.setDataHandler( new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset))); html_mp.addBodyPart(rel_bph); // Create the second BodyPart of the multipart/alternative, // set its content to the html multipart, and add the // second bodypart to the main multipart. BodyPart alt_bp2 = new MimeBodyPart(); alt_bp2.setContent(html_mp); mp.addBodyPart(alt_bp2); messageMim.setContent(mp); // RFC 822 "Date" header field // Indicates that the message is complete and ready for delivery messageMim.setSentDate(new GregorianCalendar().getTime()); // Since we used html tags, the content must be marker as text/html // messageMim.setContent(content,"text/html; charset="+charset); Transport tr = session.getTransport("smtp"); // Connect to smtp server, if needed if (needsAuth) { tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword); messageMim.saveChanges(); tr.sendMessage(messageMim, messageMim.getAllRecipients()); tr.close(); } else { // Send message Transport.send(messageMim); } } catch (SendFailedException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient, e); throw e; } catch (MessagingException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } catch (Exception e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail./*from w ww. j a va 2 s .c om*/ * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:com.sonicle.webtop.core.app.WebTopApp.java
public void sendEmail(javax.mail.Session session, boolean rich, InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc, String subject, String body, MimeBodyPart[] parts) throws MessagingException { //Session session=getGlobalMailSession(pid.getDomainId()); MimeMessage msg = new MimeMessage(session); try {/*from w ww. ja va 2 s . c o m*/ subject = MimeUtility.encodeText(subject); } catch (Exception exc) { } msg.setSubject(subject); msg.addFrom(new InternetAddress[] { from }); if (to != null) for (InternetAddress addr : to) { msg.addRecipient(Message.RecipientType.TO, addr); } if (cc != null) for (InternetAddress addr : cc) { msg.addRecipient(Message.RecipientType.CC, addr); } if (bcc != null) for (InternetAddress addr : bcc) { msg.addRecipient(Message.RecipientType.BCC, addr); } body = StringUtils.defaultString(body); MimeMultipart mp = new MimeMultipart("mixed"); if (rich) { MimeMultipart alternative = new MimeMultipart("alternative"); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(body, MailUtils.buildPartContentType("text/html", "UTF-8")); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(MailUtils.htmlToText(MailUtils.htmlunescapesource(body)), MailUtils.buildPartContentType("text/plain", "UTF-8")); alternative.addBodyPart(mbp1); alternative.addBodyPart(mbp2); MimeBodyPart altbody = new MimeBodyPart(); altbody.setContent(alternative); mp.addBodyPart(altbody); } else { MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(body, MailUtils.buildPartContentType("text/plain", "UTF-8")); mp.addBodyPart(mbp1); } if (parts != null) { for (MimeBodyPart part : parts) mp.addBodyPart(part); } msg.setContent(mp); msg.setSentDate(new java.util.Date()); Transport.send(msg); }
From source file:com.flexoodb.common.FlexUtils.java
static public boolean sendMail(String host, int port, String from, String to, String subject, String msg) throws Exception { SMTPTransport transport = null;/*from w ww . java 2 s.com*/ boolean ok = false; try { InternetAddress[] rcptto = new InternetAddress[1]; rcptto[0] = new InternetAddress(to); Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port + ""); javax.mail.Session session = javax.mail.Session.getDefaultInstance(props, null); transport = (SMTPTransport) session.getTransport("smtp"); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); message.setContent(msg, "text/html"); //Transport.send(message); transport.setLocalHost("REMOTE-CLIENT"); transport.connect(); transport.sendMessage(message, rcptto); ok = true; } catch (Exception e) { e.printStackTrace(); } finally { try { transport.close(); } catch (Exception f) { f.printStackTrace(); } } return ok; }
From source file:com.flexoodb.common.FlexUtils.java
static public String sendMailShowResult(String host, int port, String from, String to, String subject, String msg) throws Exception { String response = "OK"; SMTPTransport transport = null;/* ww w . jav a2 s .co m*/ boolean ok = true; try { InternetAddress[] rcptto = new InternetAddress[1]; rcptto[0] = new InternetAddress(to); Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port + ""); props.put("mail.smtp.connectiontimeout", "60000"); // 300000 original props.put("mail.smtp.timeout", "60000"); props.put("mail.smtp.quitwait", "false"); javax.mail.Session session = javax.mail.Session.getInstance(props); transport = (SMTPTransport) session.getTransport("smtp"); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); message.setContent(msg, "text/html"); //Transport.send(message); transport.setLocalHost("REMOTE-CLIENT"); transport.connect(); transport.sendMessage(message, rcptto); } catch (Exception e) { e.printStackTrace(); ok = false; } finally { try { if (!ok) { response = "SENDING FAILED:" + transport.getLastServerResponse(); } else { response = "SENDING SUCCESS:" + transport.getLastServerResponse(); } transport.close(); } catch (Exception f) { } } return response; }
From source file:com.openkm.util.MailUtils.java
/** * Create a mail.//from ww w . j av a 2s .com * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null && Config.SEND_MAIL_FROM_USER) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * Creates the IMAP messages to be sent. Looks up access (email & pwd) from * LDAP, sets the values and returns the messages to be sent. * // w ww. j a v a2s. c o m * @param session Mail session * @param emailAddr From email address * @param request Request from PS * @return Array of messages * @throws Exception */ private Message[] createMessage(Session session, String emailAddr, SetMessageRequestType request) throws Exception { /* //DBG ONLY - Check about CC entry. List<String> ctlist = request.getContactTo(); if (!CommonUtil.listNullorEmpty(ctlist)) { System.out.println("===> createMessage: TO="+ ctlist.get(0)); } ctlist = request.getContactCC(); if (!CommonUtil.listNullorEmpty(ctlist)) { System.out.println("===> createMessage: CC="+ ctlist.get(0)); } ctlist = request.getContactBCC(); if (!CommonUtil.listNullorEmpty(ctlist)) { System.out.println("===> createMessage: BCC="+ ctlist.get(0)); } */ MimeMessage message = new MimeMessage(session); if (!CommonUtil.listNullorEmpty(request.getContactTo())) { message.setRecipients(Message.RecipientType.TO, getInetAddresses(request.getContactTo())); //getInetAddresses(request, "To")); } if (!CommonUtil.listNullorEmpty(request.getContactCC())) { message.setRecipients(Message.RecipientType.CC, getInetAddresses(request.getContactCC())); //getInetAddresses(request, "CC")); } if (!CommonUtil.listNullorEmpty(request.getContactBCC())) { message.setRecipients(Message.RecipientType.BCC, getInetAddresses(request.getContactBCC())); //getInetAddresses(request, "BCC")); } message.setSubject(request.getSubject()); // Adding headers doesn't seem to be supported currently in zimbra. // Adding patientId to body instead temporarily // message.addHeader("X-PATIENTID", request.getPatientId()); StringBuilder sb = new StringBuilder(); // Only add in PATIENTID first line if there is a patientId in session. if (!CommonUtil.strNullorEmpty(request.getPatientId())) { sb.append("PATIENTID=").append(request.getPatientId()).append("\n"); } if (CommonUtil.strNullorEmpty(request.getBody())) { sb.append(""); } else { sb.append(request.getBody()); } message.setContent(sb.toString(), "text/plain"); message.setFrom(new InternetAddress(emailAddr)); message.setSentDate(new Date()); List<String> labelList = request.getLabels(); if (labelList.size() > 0) { String label = labelList.get(0); if (label.equalsIgnoreCase("starred")) { message.setFlag(Flags.Flag.FLAGGED, true); } } Message[] msgArr = new Message[1]; msgArr[0] = message; return msgArr; }
From source file:com.flexoodb.common.FlexUtils.java
static public String sendMailShowResult(String host, int port, String fromname, String from, String to, String subject, String msg) throws Exception { String response = "OK"; SMTPTransport transport = null;// w w w . j av a 2 s.c om boolean ok = true; try { InternetAddress[] rcptto = new InternetAddress[1]; rcptto[0] = new InternetAddress(to); Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port + ""); props.put("mail.smtp.connectiontimeout", "60000"); // 300000 original props.put("mail.smtp.timeout", "60000"); props.put("mail.smtp.quitwait", "false"); javax.mail.Session session = javax.mail.Session.getInstance(props); transport = (SMTPTransport) session.getTransport("smtp"); MimeMessage message = new MimeMessage(session); if (fromname == null || fromname.isEmpty()) { message.setFrom(new InternetAddress(from)); } else { message.setFrom(new InternetAddress(from, fromname)); } message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); message.setContent(msg, "text/html"); //Transport.send(message); transport.setLocalHost("REMOTE-CLIENT"); transport.connect(); transport.sendMessage(message, rcptto); } catch (Exception e) { e.printStackTrace(); ok = false; } finally { try { if (!ok) { response = "SENDING FAILED:" + transport.getLastServerResponse(); } else { response = "SENDING SUCCESS:" + transport.getLastServerResponse(); } transport.close(); } catch (Exception f) { } } return response; }