List of usage examples for javax.mail.internet MimeMessage setHeader
@Override public void setHeader(String name, String value) throws MessagingException
From source file:net.wastl.webmail.plugins.SendMessage.java
public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head) throws WebMailException, ServletException { if (sess1 == null) { throw new WebMailException( "No session was given. If you feel this is incorrect, please contact your system administrator"); }/*w w w. j ava 2s .c o m*/ WebMailSession session = (WebMailSession) sess1; UserData user = session.getUser(); HTMLDocument content; Locale locale = user.getPreferredLocale(); /* Save message in case there is an error */ session.storeMessage(head); if (head.isContentSet("SEND")) { /* The form was submitted, now we will send it ... */ try { MimeMessage msg = new MimeMessage(mailsession); Address from[] = new Address[1]; try { /** * Why we need * org.bulbul.util.TranscodeUtil.transcodeThenEncodeByLocale()? * * Because we specify client browser's encoding to UTF-8, IE seems * to send all data encoded in UTF-8. We have to transcode all byte * sequences we received to UTF-8, and next we encode those strings * using MimeUtility.encodeText() depending on user's locale. Since * MimeUtility.encodeText() is used to convert the strings into its * transmission format, finally we can use the strings in the * outgoing e-mail which relies on receiver's email agent to decode * the strings. * * As described in JavaMail document, MimeUtility.encodeText() conforms * to RFC2047 and as a result, we'll get strings like "=?Big5?B......". */ /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()), // MimeUtility.encodeText(session.getUser().getFullName())); from[0] = new InternetAddress( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("FROM"), null, locale), TranscodeUtil.transcodeThenEncodeByLocale(session.getUser().getFullName(), null, locale)); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); from[0] = new InternetAddress(head.getContent("FROM"), session.getUser().getFullName()); } StringTokenizer t; try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("TO"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("TO").trim(), ",;"); } /* Check To: field, when empty, throw an exception */ if (t.countTokens() < 1) { throw new MessagingException("The recipient field must not be empty!"); } Address to[] = new Address[t.countTokens()]; int i = 0; while (t.hasMoreTokens()) { to[i] = new InternetAddress(t.nextToken().trim()); i++; } try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("CC"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("CC").trim(), ",;"); } Address cc[] = new Address[t.countTokens()]; i = 0; while (t.hasMoreTokens()) { cc[i] = new InternetAddress(t.nextToken().trim()); i++; } try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("BCC"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("BCC").trim(), ",;"); } Address bcc[] = new Address[t.countTokens()]; i = 0; while (t.hasMoreTokens()) { bcc[i] = new InternetAddress(t.nextToken().trim()); i++; } session.setSent(false); msg.addFrom(from); if (to.length > 0) { msg.addRecipients(Message.RecipientType.TO, to); } if (cc.length > 0) { msg.addRecipients(Message.RecipientType.CC, cc); } if (bcc.length > 0) { msg.addRecipients(Message.RecipientType.BCC, bcc); } msg.addHeader("X-Mailer", WebMailServer.getVersion() + ", " + getName() + " plugin v" + getVersion()); String subject = null; if (!head.isContentSet("SUBJECT")) { subject = "no subject"; } else { try { // subject=MimeUtility.encodeText(head.getContent("SUBJECT")); subject = TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("SUBJECT"), "ISO8859_1", locale); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); subject = head.getContent("SUBJECT"); } } msg.addHeader("Subject", subject); if (head.isContentSet("REPLY-TO")) { // msg.addHeader("Reply-To",head.getContent("REPLY-TO")); msg.addHeader("Reply-To", TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("REPLY-TO"), "ISO8859_1", locale)); } msg.setSentDate(new Date(System.currentTimeMillis())); String contnt = head.getContent("BODY"); //String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset()); String charset = "utf-8"; MimeMultipart cont = new MimeMultipart(); MimeBodyPart txt = new MimeBodyPart(); // Transcode to UTF-8 contnt = new String(contnt.getBytes("ISO8859_1"), "UTF-8"); // Encode text if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) { txt.setText(contnt, "Big5"); txt.setHeader("Content-Type", "text/plain; charset=\"Big5\""); txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP? } else { txt.setText(contnt, "utf-8"); txt.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP? } /* Add an advertisement if the administrator requested to do so */ cont.addBodyPart(txt); if (store.getConfig("ADVERTISEMENT ATTACH").equals("YES")) { MimeBodyPart adv = new MimeBodyPart(); String file = ""; if (store.getConfig("ADVERTISEMENT SIGNATURE PATH").startsWith("/")) { file = store.getConfig("ADVERTISEMENT SIGNATURE PATH"); } else { file = parent.getProperty("webmail.data.path") + System.getProperty("file.separator") + store.getConfig("ADVERTISEMENT SIGNATURE PATH"); } String advcont = ""; try { BufferedReader fin = new BufferedReader(new FileReader(file)); String line = fin.readLine(); while (line != null && !line.equals("")) { advcont += line + "\n"; line = fin.readLine(); } fin.close(); } catch (IOException ex) { } /** * Transcode to UTF-8; Since advcont comes from file, we transcode * it from default encoding. */ // Encode text if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) { advcont = new String(advcont.getBytes(), "Big5"); adv.setText(advcont, "Big5"); adv.setHeader("Content-Type", "text/plain; charset=\"Big5\""); adv.setHeader("Content-Transfer-Encoding", "quoted-printable"); } else { advcont = new String(advcont.getBytes(), "UTF-8"); adv.setText(advcont, "utf-8"); adv.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); adv.setHeader("Content-Transfer-Encoding", "quoted-printable"); } cont.addBodyPart(adv); } for (String attachmentKey : session.getAttachments().keySet()) { ByteStore bs = session.getAttachment(attachmentKey); InternetHeaders ih = new InternetHeaders(); ih.addHeader("Content-Transfer-Encoding", "BASE64"); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(pin); /* This is used to write to the Pipe asynchronously to avoid blocking */ StreamConnector sconn = new StreamConnector(pin, (int) (bs.getSize() * 1.6) + 1000); BufferedOutputStream encoder = new BufferedOutputStream(MimeUtility.encode(pout, "BASE64")); encoder.write(bs.getBytes()); encoder.flush(); encoder.close(); //MimeBodyPart att1=sconn.getResult(); MimeBodyPart att1 = new MimeBodyPart(ih, sconn.getResult().getBytes()); if (bs.getDescription() != "") { att1.setDescription(bs.getDescription(), "utf-8"); } /** * As described in FileAttacher.java line #95, now we need to * encode the attachment file name. */ // att1.setFileName(bs.getName()); String fileName = bs.getName(); String localeCharset = getLocaleCharset(locale.getLanguage(), locale.getCountry()); String encodedFileName = MimeUtility.encodeText(fileName, localeCharset, null); if (encodedFileName.equals(fileName)) { att1.addHeader("Content-Type", bs.getContentType()); att1.setFileName(fileName); } else { att1.addHeader("Content-Type", bs.getContentType() + "; charset=" + localeCharset); encodedFileName = encodedFileName.substring(localeCharset.length() + 5, encodedFileName.length() - 2); encodedFileName = encodedFileName.replace('=', '%'); att1.addHeaderLine("Content-Disposition: attachment; filename*=" + localeCharset + "''" + encodedFileName); } cont.addBodyPart(att1); } msg.setContent(cont); // } msg.saveChanges(); boolean savesuccess = true; msg.setHeader("Message-ID", session.getUserModel().getWorkMessage().getAttribute("msgid")); if (session.getUser().wantsSaveSent()) { String folderhash = session.getUser().getSentFolder(); try { Folder folder = session.getFolder(folderhash); Message[] m = new Message[1]; m[0] = msg; folder.appendMessages(m); } catch (MessagingException e) { savesuccess = false; } catch (NullPointerException e) { // Invalid folder: savesuccess = false; } } boolean sendsuccess = false; try { Transport.send(msg); Address sent[] = new Address[to.length + cc.length + bcc.length]; int c1 = 0; int c2 = 0; for (c1 = 0; c1 < to.length; c1++) { sent[c1] = to[c1]; } for (c2 = 0; c2 < cc.length; c2++) { sent[c1 + c2] = cc[c2]; } for (int c3 = 0; c3 < bcc.length; c3++) { sent[c1 + c2 + c3] = bcc[c3]; } sendsuccess = true; throw new SendFailedException("success", new Exception("success"), sent, null, null); } catch (SendFailedException e) { session.handleTransportException(e); } //session.clearMessage(); content = new XHTMLDocument(session.getModel(), store.getStylesheet("sendresult.xsl", user.getPreferredLocale(), user.getTheme())); // if(sendsuccess) session.clearWork(); } catch (Exception e) { log.error("Could not send messsage", e); throw new DocumentNotFoundException("Could not send message. (Reason: " + e.getMessage() + ")"); } } else if (head.isContentSet("ATTACH")) { /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to have two targets without Javascript) */ content = parent.getURLHandler().handleURL("/compose/attach", session, head); } else { throw new DocumentNotFoundException("Could not send message. (Reason: No content given)"); } return content; }
From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java
@Override public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) { return new AbstractMailSendBuilder() { @Override/*from w w w .j av a 2s . c o m*/ public void send(final String content) throws Exception { __sendExecPool.execute(new Runnable() { @Override public void run() { try { MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed()); // for (String _to : getTo()) { _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to)); } for (String _cc : getCc()) { _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc)); } for (String _bcc : getBcc()) { _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc)); } // if (getLevel() != null) { switch (getLevel()) { case LEVEL_HIGH: _message.setHeader("X-MSMail-Priority", "High"); _message.setHeader("X-Priority", "1"); break; case LEVEL_NORMAL: _message.setHeader("X-MSMail-Priority", "Normal"); _message.setHeader("X-Priority", "3"); break; case LEVEL_LOW: _message.setHeader("X-MSMail-Priority", "Low"); _message.setHeader("X-Priority", "5"); break; default: } } // String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8"); _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(), serverCfgMeta.getDisplayName(), _charset)); _message.setSubject(getSubject(), _charset); // Multipart _container = new MimeMultipart(); // MimeBodyPart _textBodyPart = new MimeBodyPart(); if (getMimeType() == null) { mimeType(IMailSender.MimeType.TEXT_PLAIN); } _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset); _container.addBodyPart(_textBodyPart); // ??<img src="cid:<CID_NAME>"> for (PairObject<String, File> _file : getAttachments()) { if (_file.getValue() != null) { MimeBodyPart _fileBodyPart = new MimeBodyPart(); FileDataSource _fileDS = new FileDataSource(_file.getValue()); _fileBodyPart.setDataHandler(new DataHandler(_fileDS)); if (_file.getKey() != null) { _fileBodyPart.setHeader("Content-ID", _file.getKey()); } _fileBodyPart.setFileName(_fileDS.getName()); _container.addBodyPart(_fileBodyPart); } } // ?? _message.setContent(_container); Transport.send(_message); } catch (Exception e) { throw new RuntimeException(RuntimeUtils.unwrapThrow(e)); } } }); } }; }
From source file:nl.nn.adapterframework.senders.MailSender.java
protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType, String messageBase64, String charset, Collection recipients, Collection attachments) throws SenderException { StringBuffer sb = new StringBuffer(); if (recipients == null || recipients.size() == 0) { throw new SenderException("MailSender [" + getName() + "] has no recipients for message"); }//from w w w. ja va 2s . c om if (StringUtils.isEmpty(from)) { from = defaultFrom; } if (StringUtils.isEmpty(subject)) { subject = defaultSubject; } log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject + "] to #recipients [" + recipients.size() + "]"); if (StringUtils.isEmpty(messageType)) { messageType = defaultMessageType; } if (StringUtils.isEmpty(messageBase64)) { messageBase64 = defaultMessageBase64; } try { if (log.isDebugEnabled()) { sb.append("MailSender [" + getName() + "] sending message "); sb.append("[smtpHost=" + smtpHost); sb.append("[from=" + from + "]"); sb.append("[subject=" + subject + "]"); sb.append("[threadTopic=" + threadTopic + "]"); sb.append("[text=" + message + "]"); sb.append("[type=" + messageType + "]"); sb.append("[base64=" + messageBase64 + "]"); } if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) { message = decodeBase64ToString(message); } // construct a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, charset); if (StringUtils.isNotEmpty(threadTopic)) { msg.setHeader("Thread-Topic", threadTopic); } Iterator iter = recipients.iterator(); boolean recipientsFound = false; while (iter.hasNext()) { Element recipientElement = (Element) iter.next(); String recipient = XmlUtils.getStringValue(recipientElement); if (StringUtils.isNotEmpty(recipient)) { String typeAttr = recipientElement.getAttribute("type"); Message.RecipientType recipientType = Message.RecipientType.TO; if ("cc".equalsIgnoreCase(typeAttr)) { recipientType = Message.RecipientType.CC; } if ("bcc".equalsIgnoreCase(typeAttr)) { recipientType = Message.RecipientType.BCC; } msg.addRecipient(recipientType, new InternetAddress(recipient)); recipientsFound = true; if (log.isDebugEnabled()) { sb.append("[recipient(" + typeAttr + ")=" + recipient + "]"); } } else { log.debug("empty recipient found, ignoring"); } } if (!recipientsFound) { throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients"); } String messageTypeWithCharset; if (charset == null) { charset = System.getProperty("mail.mime.charset"); if (charset == null) { charset = System.getProperty("file.encoding"); } } if (charset != null) { messageTypeWithCharset = messageType + ";charset=" + charset; } else { messageTypeWithCharset = messageType; } log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]"); if (attachments == null || attachments.size() == 0) { //msg.setContent(message, messageType); msg.setContent(message, messageTypeWithCharset); } else { Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); //messageBodyPart.setContent(message, messageType); messageBodyPart.setContent(message, messageTypeWithCharset); multipart.addBodyPart(messageBodyPart); iter = attachments.iterator(); while (iter.hasNext()) { Element attachmentElement = (Element) iter.next(); String attachmentText = XmlUtils.getStringValue(attachmentElement); String attachmentName = attachmentElement.getAttribute("name"); String attachmentUrl = attachmentElement.getAttribute("url"); String attachmentType = attachmentElement.getAttribute("type"); String attachmentBase64 = attachmentElement.getAttribute("base64"); if (StringUtils.isEmpty(attachmentType)) { attachmentType = getDefaultAttachmentType(); } if (StringUtils.isEmpty(attachmentName)) { attachmentName = getDefaultAttachmentName(); } log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url [" + attachmentUrl + "]contents [" + attachmentText + "]"); messageBodyPart = new MimeBodyPart(); DataSource attachmentDataSource; if (!StringUtils.isEmpty(attachmentUrl)) { attachmentDataSource = new URLDataSource(new URL(attachmentUrl)); messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource)); } messageBodyPart.setFileName(attachmentName); if ("true".equalsIgnoreCase(attachmentBase64)) { messageBodyPart.setDataHandler(decodeBase64(attachmentText)); } else { messageBodyPart.setText(attachmentText); } multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); } log.debug(sb.toString()); msg.setSentDate(new Date()); msg.saveChanges(); // send the message putOnTransport(msg); // return the mail in mail-safe from ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); byte[] byteArray = out.toByteArray(); return Misc.byteArrayToString(byteArray, "\n", false); } catch (Exception e) { throw new SenderException("MailSender got error", e); } }
From source file:nl.nn.adapterframework.senders.MailSenderOld.java
protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType, String messageBase64, String charset, Collection<Recipient> recipients, Collection<Attachment> attachments) throws SenderException { StringBuffer sb = new StringBuffer(); if (recipients == null || recipients.size() == 0) { throw new SenderException("MailSender [" + getName() + "] has no recipients for message"); }/*from ww w . j a va2s .c o m*/ if (StringUtils.isEmpty(from)) { from = defaultFrom; } if (StringUtils.isEmpty(subject)) { subject = defaultSubject; } log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject + "] to #recipients [" + recipients.size() + "]"); if (StringUtils.isEmpty(messageType)) { messageType = defaultMessageType; } if (StringUtils.isEmpty(messageBase64)) { messageBase64 = defaultMessageBase64; } try { if (log.isDebugEnabled()) { sb.append("MailSender [" + getName() + "] sending message "); sb.append("[smtpHost=" + smtpHost); sb.append("[from=" + from + "]"); sb.append("[subject=" + subject + "]"); sb.append("[threadTopic=" + threadTopic + "]"); sb.append("[text=" + message + "]"); sb.append("[type=" + messageType + "]"); sb.append("[base64=" + messageBase64 + "]"); } if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) { message = decodeBase64ToString(message); } // construct a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, charset); if (StringUtils.isNotEmpty(threadTopic)) { msg.setHeader("Thread-Topic", threadTopic); } Iterator iter = recipients.iterator(); boolean recipientsFound = false; while (iter.hasNext()) { Recipient recipient = (Recipient) iter.next(); String value = recipient.value; String type = recipient.type; Message.RecipientType recipientType; if ("cc".equalsIgnoreCase(type)) { recipientType = Message.RecipientType.CC; } else if ("bcc".equalsIgnoreCase(type)) { recipientType = Message.RecipientType.BCC; } else { recipientType = Message.RecipientType.TO; } msg.addRecipient(recipientType, new InternetAddress(value)); recipientsFound = true; if (log.isDebugEnabled()) { sb.append("[recipient [" + recipient + "]]"); } } if (!recipientsFound) { throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients"); } String messageTypeWithCharset; if (charset == null) { charset = System.getProperty("mail.mime.charset"); if (charset == null) { charset = System.getProperty("file.encoding"); } } if (charset != null) { messageTypeWithCharset = messageType + ";charset=" + charset; } else { messageTypeWithCharset = messageType; } log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]"); if (attachments == null || attachments.size() == 0) { //msg.setContent(message, messageType); msg.setContent(message, messageTypeWithCharset); } else { Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); //messageBodyPart.setContent(message, messageType); messageBodyPart.setContent(message, messageTypeWithCharset); multipart.addBodyPart(messageBodyPart); int counter = 0; iter = attachments.iterator(); while (iter.hasNext()) { counter++; Attachment attachment = (Attachment) iter.next(); Object value = attachment.getValue(); String name = attachment.getName(); if (StringUtils.isEmpty(name)) { name = getDefaultAttachmentName() + counter; } log.debug("found attachment [" + attachment + "]"); messageBodyPart = new MimeBodyPart(); messageBodyPart.setFileName(name); if (value instanceof DataHandler) { messageBodyPart.setDataHandler((DataHandler) value); } else { messageBodyPart.setText((String) value); } multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); } log.debug(sb.toString()); msg.setSentDate(new Date()); msg.saveChanges(); // send the message putOnTransport(msg); // return the mail in mail-safe from ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); byte[] byteArray = out.toByteArray(); return Misc.byteArrayToString(byteArray, "\n", false); } catch (Exception e) { throw new SenderException("MailSender got error", e); } }
From source file:org.alfresco.repo.action.executer.MailActionExecuter.java
public MimeMessageHelper prepareEmail(final Action ruleAction, final NodeRef actionedUponNodeRef, final Pair<String, Locale> recipient, final Pair<InternetAddress, Locale> sender) { // Create the mime mail message. // Hack: using an array here to get around the fact that inner classes aren't closures. // The MimeMessagePreparator.prepare() signature does not allow us to return a value and yet // we can't set a result on a bare, non-final object reference due to Java language restrictions. final MimeMessageHelper[] messageRef = new MimeMessageHelper[1]; MimeMessagePreparator mailPreparer = new MimeMessagePreparator() { @SuppressWarnings("unchecked") public void prepare(MimeMessage mimeMessage) throws MessagingException { if (logger.isDebugEnabled()) { logger.debug(ruleAction.getParameterValues()); }// www . j ava 2 s. c om messageRef[0] = new MimeMessageHelper(mimeMessage); // set header encoding if one has been supplied if (headerEncoding != null && headerEncoding.length() != 0) { mimeMessage.setHeader("Content-Transfer-Encoding", headerEncoding); } // set recipient String to = (String) ruleAction.getParameterValue(PARAM_TO); if (to != null && to.length() != 0) { messageRef[0].setTo(to); // Note: there is no validation on the username to check that it actually is an email address. // TODO Fix this. Serializable ccValue = (String) ruleAction.getParameterValue(PARAM_CC); if (ccValue != null) { if (ccValue instanceof String) { String cc = (String) ccValue; if (cc.length() > 0) { messageRef[0].setCc(cc); } } else if (ccValue instanceof List<?>) { List<String> s = (List<String>) ccValue; messageRef[0].setCc((String[]) s.toArray()); } else if (ccValue.getClass().isArray()) { messageRef[0].setCc((String[]) ccValue); } } Serializable bccValue = (String) ruleAction.getParameterValue(PARAM_BCC); if (bccValue != null) { if (bccValue instanceof String) { String bcc = (String) bccValue; if (bcc.length() > 0) { messageRef[0].setBcc(bcc); } } else if (bccValue instanceof List<?>) { List<String> s = (List<String>) bccValue; messageRef[0].setBcc((String[]) s.toArray()); } else if (bccValue.getClass().isArray()) { messageRef[0].setCc((String[]) bccValue); } } } else { // see if multiple recipients have been supplied - as a list of authorities Serializable authoritiesValue = ruleAction.getParameterValue(PARAM_TO_MANY); List<String> authorities = null; if (authoritiesValue != null) { if (authoritiesValue instanceof String) { authorities = new ArrayList<String>(1); authorities.add((String) authoritiesValue); } else { authorities = (List<String>) authoritiesValue; } } if (authorities != null && authorities.size() != 0) { List<String> recipients = new ArrayList<String>(authorities.size()); if (logger.isTraceEnabled()) { logger.trace(authorities.size() + " recipient(s) for mail"); } for (String authority : authorities) { final AuthorityType authType = AuthorityType.getAuthorityType(authority); if (logger.isTraceEnabled()) { logger.trace(" authority type: " + authType); } if (authType.equals(AuthorityType.USER)) { if (personService.personExists(authority) == true) { NodeRef person = personService.getPerson(authority); if (!personService.isEnabled(authority) && !nodeService.hasAspect(person, ContentModel.ASPECT_ANULLABLE)) { continue; } String address = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); if (address != null && address.length() != 0 && validateAddress(address)) { if (logger.isTraceEnabled()) { logger.trace("Recipient (person) exists in Alfresco with known email."); } recipients.add(address); } else { if (logger.isTraceEnabled()) { logger.trace( "Recipient (person) exists in Alfresco without known email."); } // If the username looks like an email address, we'll use that. if (validateAddress(authority)) { recipients.add(authority); } } } else { if (logger.isTraceEnabled()) { logger.trace("Recipient does not exist in Alfresco."); } if (validateAddress(authority)) { recipients.add(authority); } } } else if (authType.equals(AuthorityType.GROUP) || authType.equals(AuthorityType.EVERYONE)) { if (logger.isTraceEnabled()) { logger.trace("Recipient is a group..."); } // Notify all members of the group Set<String> users; if (authType.equals(AuthorityType.GROUP)) { users = authorityService.getContainedAuthorities(AuthorityType.USER, authority, false); } else { users = authorityService.getAllAuthorities(AuthorityType.USER); } for (String userAuth : users) { if (personService.personExists(userAuth) == true) { if (!personService.isEnabled(userAuth)) { continue; } NodeRef person = personService.getPerson(userAuth); String address = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); if (address != null && address.length() != 0) { recipients.add(address); if (logger.isTraceEnabled()) { logger.trace(" Group member email is known."); } } else { if (logger.isTraceEnabled()) { logger.trace(" Group member email not known."); } if (validateAddress(authority)) { recipients.add(userAuth); } } } else { if (logger.isTraceEnabled()) { logger.trace(" Group member person not found"); } if (validateAddress(authority)) { recipients.add(userAuth); } } } } } if (logger.isTraceEnabled()) { logger.trace(recipients.size() + " valid recipient(s)."); } if (recipients.size() > 0) { messageRef[0].setTo(recipients.toArray(new String[recipients.size()])); } else { // All recipients were invalid throw new MailPreparationException("All recipients for the mail action were invalid"); } } else { // No recipients have been specified throw new MailPreparationException("No recipient has been specified for the mail action"); } } // from person - not to be performed for the "admin" or "system" users NodeRef fromPerson = null; final String currentUserName = authService.getCurrentUserName(); final List<String> usersNotToBeUsedInFromField = Arrays.asList(new String[] { AuthenticationUtil.getSystemUserName(), AuthenticationUtil.getGuestUserName() }); if (!usersNotToBeUsedInFromField.contains(currentUserName)) { fromPerson = personService.getPerson(currentUserName); } if (isFromEnabled()) { // Use the FROM parameter in preference to calculating values. String from = (String) ruleAction.getParameterValue(PARAM_FROM); if (from != null && from.length() > 0) { if (logger.isDebugEnabled()) { logger.debug("from specified as a parameter, from:" + from); } // Check whether or not to use a personal name for the email (will be RFC 2047 encoded) String fromPersonalName = (String) ruleAction.getParameterValue(PARAM_FROM_PERSONAL_NAME); if (fromPersonalName != null && fromPersonalName.length() > 0) { try { messageRef[0].setFrom(from, fromPersonalName); } catch (UnsupportedEncodingException error) { // Uses the JVM's default encoding, can never be unsupported. Just in case, revert to simple email messageRef[0].setFrom(from); } } else { messageRef[0].setFrom(from); } } else { // set the from address from the current user String fromActualUser = null; if (fromPerson != null) { fromActualUser = (String) nodeService.getProperty(fromPerson, ContentModel.PROP_EMAIL); } if (fromActualUser != null && fromActualUser.length() != 0) { if (logger.isDebugEnabled()) { logger.debug("looked up email address for :" + fromPerson + " email from " + fromActualUser); } messageRef[0].setFrom(fromActualUser); } else { // from system or user does not have email address messageRef[0].setFrom(fromDefaultAddress); } } } else { if (logger.isDebugEnabled()) { logger.debug("from not enabled - sending from default address:" + fromDefaultAddress); } // from is not enabled. messageRef[0].setFrom(fromDefaultAddress); } // set subject line messageRef[0].setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT)); if ((testModeRecipient != null) && (testModeRecipient.length() > 0) && (!testModeRecipient.equals("${dev.email.recipient.address}"))) { // If we have an override for the email recipient, we'll send the email to that address instead. // We'll prefix the subject with the original recipient, but leave the email message unchanged in every other way. messageRef[0].setTo(testModeRecipient); String emailRecipient = (String) ruleAction.getParameterValue(PARAM_TO); if (emailRecipient == null) { Object obj = ruleAction.getParameterValue(PARAM_TO_MANY); if (obj != null) { emailRecipient = obj.toString(); } } String recipientPrefixedSubject = "(" + emailRecipient + ") " + (String) ruleAction.getParameterValue(PARAM_SUBJECT); messageRef[0].setSubject(recipientPrefixedSubject); } // See if an email template has been specified String text = null; // templateRef: either a nodeRef or classpath (see ClasspathRepoTemplateLoader) Serializable ref = ruleAction.getParameterValue(PARAM_TEMPLATE); String templateRef = (ref instanceof NodeRef ? ((NodeRef) ref).toString() : (String) ref); if (templateRef != null) { Map<String, Object> suppliedModel = null; if (ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL) != null) { Object m = ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL); if (m instanceof Map) { suppliedModel = (Map<String, Object>) m; } else { logger.warn("Skipping unsupported email template model parameters of type " + m.getClass().getName() + " : " + m.toString()); } } // build the email template model Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, suppliedModel, fromPerson); // Determine the locale to use to send the email. Locale locale = recipient.getSecond(); if (locale == null) { locale = (Locale) ruleAction.getParameterValue(PARAM_LOCALE); } if (locale == null) { locale = sender.getSecond(); } // set subject line String subject = (String) ruleAction.getParameterValue(PARAM_SUBJECT); Object subjectParamsObject = ruleAction.getParameterValue(PARAM_SUBJECT_PARAMS); Object[] subjectParams = null; //Javasctipt pass SubjectParams as ArrayList. see MNT-12534 if (subjectParamsObject instanceof List) { subjectParams = ((List<Object>) subjectParamsObject).toArray(); } else if (subjectParamsObject instanceof Object[]) { subjectParams = (Object[]) subjectParamsObject; } else { if (subjectParamsObject != null) { subjectParams = new Object[] { subjectParamsObject.toString() }; } } String localizedSubject = getLocalizedSubject(subject, subjectParams, locale); if (locale == null) { // process the template against the model text = templateService.processTemplate("freemarker", templateRef, model); } else { // process the template against the model text = templateService.processTemplate("freemarker", templateRef, model, locale); } if ((testModeRecipient != null) && (testModeRecipient.length() > 0) && (!testModeRecipient.equals("${dev.email.recipient.address}"))) { // If we have an override for the email recipient, we'll send the email to that address instead. // We'll prefix the subject with the original recipient, but leave the email message unchanged in every other way. messageRef[0].setTo(testModeRecipient); String emailRecipient = recipient.getFirst(); String recipientPrefixedSubject = "(" + emailRecipient + ") " + localizedSubject; messageRef[0].setSubject(recipientPrefixedSubject); } else { messageRef[0].setTo(recipient.getFirst()); messageRef[0].setSubject(localizedSubject); } } // set the text body of the message boolean isHTML = false; if (text == null) { text = (String) ruleAction.getParameterValue(PARAM_TEXT); } if (text != null) { if (isHTML(text)) { isHTML = true; } } else { text = (String) ruleAction.getParameterValue(PARAM_HTML); if (text != null) { // assume HTML isHTML = true; } } if (text != null) { messageRef[0].setText(text, isHTML); } } }; MimeMessage mimeMessage = mailService.createMimeMessage(); try { mailPreparer.prepare(mimeMessage); } catch (Exception e) { // We're forced to catch java.lang.Exception here. Urgh. if (logger.isWarnEnabled()) { logger.warn("Unable to prepare mail message. Skipping.", e); } return null; } return messageRef[0]; }
From source file:org.apache.axis2.transport.mail.EMailSender.java
public void send() throws AxisFault { try {//from w w w . j a v a 2 s. c o m Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return passwordAuthentication; } }); MimeMessage msg = new MimeMessage(session); // Set date - required by rfc2822 msg.setSentDate(new java.util.Date()); // Set from - required by rfc2822 String from = properties.getProperty("mail.smtp.from"); if (from != null) { msg.setFrom(new InternetAddress(from)); } EndpointReference epr = null; MailToInfo mailToInfo; if (messageContext.getTo() != null && !messageContext.getTo().hasAnonymousAddress()) { epr = messageContext.getTo(); } if (epr != null) { if (!epr.hasNoneAddress()) { mailToInfo = new MailToInfo(epr); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress())); } else { if (from != null) { mailToInfo = new MailToInfo(from); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress())); } else { String error = EMailSender.class.getName() + "Couldn't countinue due to" + " FROM addressing is NULL"; log.error(error); throw new AxisFault(error); } } } else { // replyto : from : or reply-path; if (from != null) { mailToInfo = new MailToInfo(from); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress())); } else { String error = EMailSender.class.getName() + "Couldn't countinue due to" + " FROM addressing is NULL and EPR is NULL"; log.error(error); throw new AxisFault(error); } } msg.setSubject("__ Axis2/Java Mail Message __"); if (mailToInfo.isxServicePath()) { msg.setHeader(Constants.X_SERVICE_PATH, "\"" + mailToInfo.getContentDescription() + "\""); } if (inReplyTo != null) { msg.setHeader(Constants.IN_REPLY_TO, inReplyTo); } createMailMimeMessage(msg, mailToInfo, format); Transport.send(msg); log.info("Message being send. [Action = ]" + messageContext.getOptions().getAction()); sendReceive(messageContext, msg.getMessageID()); } catch (AddressException e) { throw new AxisFault(e.getMessage(), e); } catch (MessagingException e) { throw new AxisFault(e.getMessage(), e); } }
From source file:org.apache.axis2.transport.mail.MailClient.java
public void sendMessage(String to, String subject, String content, String soapAction) throws MessagingException { log.info("SENDING message from " + from + " to " + to); MimeMessage msg = new MimeMessage(session); msg.setHeader("transport.mail.soapaction", soapAction); msg.addRecipients(Message.RecipientType.TO, to); msg.setSubject(subject);//from ww w . j av a 2 s . c o m msg.setText(content); Transport.send(msg); }
From source file:org.apache.camel.component.mail.MailBinding.java
protected String populateContentOnMimeMessage(MimeMessage part, MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException { String contentType = determineContentType(configuration, exchange); if (LOG.isTraceEnabled()) { LOG.trace("Using Content-Type " + contentType + " for MimeMessage: " + part); }//from w w w. ja v a2 s . c o m // always store content in a byte array data store to avoid various content type and charset issues DataSource ds = new ByteArrayDataSource(exchange.getIn().getBody(String.class), contentType); part.setDataHandler(new DataHandler(ds)); // set the content type header afterwards part.setHeader("Content-Type", contentType); return contentType; }
From source file:org.apache.camel.component.mail.MailBinding.java
/** * Extracts the body from the Mail message *//*from www . j a v a2 s. c o m*/ public Object extractBodyFromMail(Exchange exchange, MailMessage mailMessage) { Message message = mailMessage.getMessage(); try { return message.getContent(); } catch (Exception e) { // try to fix message in case it has an unsupported encoding in the Content-Type header UnsupportedEncodingException uee = ObjectHelper.getException(UnsupportedEncodingException.class, e); if (uee != null) { LOG.debug("Unsupported encoding detected: " + uee.getMessage()); try { String contentType = message.getContentType(); String type = ObjectHelper.before(contentType, "charset="); if (type != null) { // try again with fixed content type LOG.debug("Trying to extract mail message again with fixed Content-Type: " + type); // Since message is read-only, we need to use a copy MimeMessage messageCopy = new MimeMessage((MimeMessage) message); messageCopy.setHeader("Content-Type", type); Object body = messageCopy.getContent(); // If we got this far, our fix worked... // Replace the MailMessage's Message with the copy mailMessage.setMessage(messageCopy); return body; } } catch (Exception e2) { // fall through and let original exception be thrown } } throw new RuntimeCamelException("Failed to extract body due to: " + e.getMessage() + ". Exchange: " + exchange + ". Message: " + message, e); } }
From source file:org.apache.camel.component.mail.MailBinding.java
/** * Appends the Mail headers from the Camel {@link MailMessage} *///from w w w .j a v a 2s .c o m protected void appendHeadersFromCamelMessage(MimeMessage mimeMessage, MailConfiguration configuration, Exchange exchange) throws MessagingException { for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) { String headerName = entry.getKey(); Object headerValue = entry.getValue(); if (headerValue != null) { if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(headerName, headerValue, exchange)) { if (headerName.equalsIgnoreCase("subject")) { mimeMessage.setSubject(asString(exchange, headerValue), IOConverter.getCharsetName(exchange, false)); continue; } if (isRecipientHeader(headerName)) { // skip any recipients as they are handled specially continue; } // alternative body should also be skipped if (headerName.equalsIgnoreCase(configuration.getAlternativeBodyHeader())) { // skip alternative body continue; } // Mail messages can repeat the same header... if (ObjectConverter.isCollection(headerValue)) { Iterator iter = ObjectHelper.createIterator(headerValue); while (iter.hasNext()) { Object value = iter.next(); mimeMessage.addHeader(headerName, asString(exchange, value)); } } else { mimeMessage.setHeader(headerName, asString(exchange, headerValue)); } } } } }