List of usage examples for javax.mail.internet MimeMessage setSentDate
@Override public void setSentDate(Date d) throws MessagingException
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
private MimeMessage createForwardMimeMessage(Address from, Address to, String subject, String body, List<DBMailAttachment> attachments, MailerResult result) { try {// ww w.ja v a2s .co m Address convertedFrom = getRawEmailFromAddress(from); MimeMessage msg = createMessage(convertedFrom); msg.setFrom(from); msg.setSubject(subject, "utf-8"); if (to != null) { msg.addRecipient(RecipientType.TO, to); } if (attachments != null && !attachments.isEmpty()) { // with attachment use multipart message Multipart multipart = new MimeMultipart(); // 1) add body part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); // 2) add attachments for (DBMailAttachment attachment : attachments) { // abort if attachment does not exist if (attachment == null || attachment.getSize() <= 0) { result.setReturnCode(MailerResult.ATTACHMENT_INVALID); logError("Tried to send mail wit attachment that does not exist::" + (attachment == null ? null : attachment.getName()), null); return msg; } messageBodyPart = new MimeBodyPart(); VFSLeaf data = getAttachmentDatas(attachment); DataSource source = new VFSDataSource(attachment.getName(), attachment.getMimetype(), data); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); } // Put parts in message msg.setContent(multipart); } else { // without attachment everything is easy, just set as text msg.setText(body, "utf-8"); } msg.setSentDate(new Date()); msg.saveChanges(); return msg; } catch (MessagingException e) { logError("", e); return null; } }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail from a Mail object// www. j a v a 2s . co m */ public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({})", mail); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (mail.getFrom() != null) { InternetAddress from = new InternetAddress(mail.getFrom()); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[mail.getTo().length]; int i = 0; for (String strTo : mail.getTo()) { to[i++] = new InternetAddress(strTo); } // Build a multiparted mail with HTML and text content for better SPAM behaviour MimeMultipart content = new MimeMultipart(); if (Mail.MIME_TEXT.equals(mail.getMimeType())) { // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } else if (Mail.MIME_HTML.equals(mail.getMimeType())) { // 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(mail.getContent()); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html"); htmlPart.setHeader("Content-Type", "text/html"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); } else { log.warn("Email does not specify content MIME type"); // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } for (Document doc : mail.getAttachments()) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(doc.getPath()); try { is = OKMDocument.getInstance().getContent(token, doc.getPath(), false); File tmp = File.createTempFile("okm", ".tmp"); fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmp.getPath()); docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(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(mail.getSubject(), "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:davmail.exchange.dav.DavExchangeSession.java
/** * @inheritDoc/*w w w . j a v a 2s .c o m*/ */ @Override protected byte[] getContent(ExchangeSession.Message message) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream contentInputStream; try { try { try { contentInputStream = getContentInputStream(message.messageUrl); } catch (UnknownHostException e) { // failover for misconfigured Exchange server, replace host name in url restoreHostName = true; contentInputStream = getContentInputStream(message.messageUrl); } } catch (HttpNotFoundException e) { LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl"); contentInputStream = getContentInputStream(message.permanentUrl); } try { IOUtil.write(contentInputStream, baos); } finally { contentInputStream.close(); } } catch (LoginTimeoutException e) { // throw error on expired session LOGGER.warn(e.getMessage()); throw e; } catch (IOException e) { LOGGER.warn("Broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl + ", trying to rebuild from properties"); try { DavPropertyNameSet messageProperties = new DavPropertyNameSet(); messageProperties.add(Field.getPropertyName("contentclass")); messageProperties.add(Field.getPropertyName("message-id")); messageProperties.add(Field.getPropertyName("from")); messageProperties.add(Field.getPropertyName("to")); messageProperties.add(Field.getPropertyName("cc")); messageProperties.add(Field.getPropertyName("subject")); messageProperties.add(Field.getPropertyName("date")); messageProperties.add(Field.getPropertyName("htmldescription")); messageProperties.add(Field.getPropertyName("body")); PropFindMethod propFindMethod = new PropFindMethod(encodeAndFixUrl(message.permanentUrl), messageProperties, 0); DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod); MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus(); if (responses.getResponses().length > 0) { MimeMessage mimeMessage = new MimeMessage((Session) null); DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK); String propertyValue = getPropertyIfExists(properties, "contentclass"); if (propertyValue != null) { mimeMessage.addHeader("Content-class", propertyValue); } propertyValue = getPropertyIfExists(properties, "date"); if (propertyValue != null) { mimeMessage.setSentDate(parseDateFromExchange(propertyValue)); } propertyValue = getPropertyIfExists(properties, "from"); if (propertyValue != null) { mimeMessage.addHeader("From", propertyValue); } propertyValue = getPropertyIfExists(properties, "to"); if (propertyValue != null) { mimeMessage.addHeader("To", propertyValue); } propertyValue = getPropertyIfExists(properties, "cc"); if (propertyValue != null) { mimeMessage.addHeader("Cc", propertyValue); } propertyValue = getPropertyIfExists(properties, "subject"); if (propertyValue != null) { mimeMessage.setSubject(propertyValue); } propertyValue = getPropertyIfExists(properties, "htmldescription"); if (propertyValue != null) { mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8"); } else { propertyValue = getPropertyIfExists(properties, "body"); if (propertyValue != null) { mimeMessage.setText(propertyValue); } } mimeMessage.writeTo(baos); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray())); } } catch (IOException e2) { LOGGER.warn(e2); } catch (DavException e2) { LOGGER.warn(e2); } catch (MessagingException e2) { LOGGER.warn(e2); } // other exception if (baos.size() == 0 && Settings.getBooleanProperty("davmail.deleteBroken")) { LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl); try { message.delete(); } catch (IOException ioe) { LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl); } throw e; } } return baos.toByteArray(); }
From source file:org.pentaho.platform.util.Emailer.java
public boolean send() { String from = props.getProperty("mail.from.default"); String fromName = props.getProperty("mail.from.name"); String to = props.getProperty("to"); String cc = props.getProperty("cc"); String bcc = props.getProperty("bcc"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject + "' and the body " + body); try {//from w ww. j a v a 2 s .c o m // Get a Session object Session session; if (authenticate) { session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } final MimeMessage msg; if (EMBEDDED_HTML.equals(attachmentMimeType)) { //Message is ready msg = new MimeMessage(session, attachment); if (body != null) { //We need to add message to the top of the email body final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent(); final MimeMultipart newMultipart = new MimeMultipart("related"); for (int i = 0; i < oldMultipart.getCount(); i++) { BodyPart bodyPart = oldMultipart.getBodyPart(i); final Object content = bodyPart.getContent(); //Main HTML body if (content instanceof String) { final String newContent = body + "<br/><br/>" + content; final MimeBodyPart part = new MimeBodyPart(); part.setText(newContent, "UTF-8", "html"); newMultipart.addBodyPart(part); } else { //CID attachments newMultipart.addBodyPart(bodyPart); } } msg.setContent(newMultipart); } } else { // construct the message msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (attachment == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType); if (body != null) { MimeBodyPart bodyMessagePart = new MimeBodyPart(); bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding()); multipart.addBodyPart(bodyMessagePart); } // attach the file to the message MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null)); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); } if (from != null) { msg.setFrom(new InternetAddress(from, fromName)); } else { // There should be no way to get here logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
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 www .j a v a2s . 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.olat.core.util.mail.manager.MailManagerImpl.java
@Override public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject, String body, List<File> attachments, MailerResult result) { try {/*from w ww.jav a 2 s . co m*/ // see FXOLAT-74: send all mails as <fromemail> (in config) to have a valid reverse lookup and therefore pass spam protection. // following doesn't work correctly, therefore add bounce-address in message already Address convertedFrom = getRawEmailFromAddress(from); MimeMessage msg = createMessage(convertedFrom); Address viewableFrom = createAddressWithName(WebappHelper.getMailConfig("mailFrom"), WebappHelper.getMailConfig("mailFromName")); msg.setFrom(viewableFrom); msg.setSubject(subject, "utf-8"); // reply to can only be an address without name (at least for postfix!), see FXOLAT-312 msg.setReplyTo(new Address[] { convertedFrom }); if (tos != null && tos.length > 0) { msg.addRecipients(RecipientType.TO, tos); } if (ccs != null && ccs.length > 0) { msg.addRecipients(RecipientType.CC, ccs); } if (bccs != null && bccs.length > 0) { msg.addRecipients(RecipientType.BCC, bccs); } if (attachments != null && !attachments.isEmpty()) { // with attachment use multipart message Multipart multipart = new MimeMultipart("mixed"); // 1) add body part if (StringHelper.isHtml(body)) { Multipart alternativePart = createMultipartAlternative(body); MimeBodyPart wrap = new MimeBodyPart(); wrap.setContent(alternativePart); multipart.addBodyPart(wrap); } else { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); } // 2) add attachments for (File attachmentFile : attachments) { // abort if attachment does not exist if (attachmentFile == null || !attachmentFile.exists()) { result.setReturnCode(MailerResult.ATTACHMENT_INVALID); logError("Tried to send mail wit attachment that does not exist::" + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null); return msg; } BodyPart filePart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFile); filePart.setDataHandler(new DataHandler(source)); filePart.setFileName(attachmentFile.getName()); multipart.addBodyPart(filePart); } // Put parts in message msg.setContent(multipart); } else { // without attachment everything is easy, just set as text if (StringHelper.isHtml(body)) { msg.setContent(createMultipartAlternative(body)); } else { msg.setText(body, "utf-8"); } } msg.setSentDate(new Date()); msg.saveChanges(); return msg; } catch (AddressException e) { result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR); logError("", e); return null; } catch (MessagingException e) { result.setReturnCode(MailerResult.SEND_GENERAL_ERROR); logError("", e); return null; } catch (UnsupportedEncodingException e) { result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR); logError("", e); return null; } }
From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java
@Override public boolean executeAction() { EmailAction emailAction = (EmailAction) getActionDefinition(); String messagePlain = emailAction.getMessagePlain().getStringValue(); String messageHtml = emailAction.getMessageHtml().getStringValue(); String subject = emailAction.getSubject().getStringValue(); String to = emailAction.getTo().getStringValue(); String cc = emailAction.getCc().getStringValue(); String bcc = emailAction.getBcc().getStringValue(); String from = emailAction.getFrom().getStringValue(defaultFrom); if (from.trim().length() == 0) { from = defaultFrom;/* www . j a v a 2 s .c om*/ } /* * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter = * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter( * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context, * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if ( * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it = * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if ( * attachData != null ) { attachments.add( attachData ); } } } } * * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" ) * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value } * * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0; * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } } */ if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$ } if ((to == null) || (to.trim().length() == 0)) { // Get the output stream that the feedback is going into OutputStream feedbackStream = getFeedbackOutputStream(); if (feedbackStream != null) { createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$ "", "", true); //$NON-NLS-1$ //$NON-NLS-2$ setFeedbackMimeType("text/html"); //$NON-NLS-1$ return true; } else { return false; } } if (subject == null) { error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$ return false; } if ((messagePlain == null) && (messageHtml == null)) { error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$ return false; } if (getRuntimeContext().isPromptPending()) { return true; } try { Properties props = new Properties(); final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService", PentahoSessionHolder.getSession()); props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost()); props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort())); props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol()); props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls())); props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate())); props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl())); props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait())); props.put("mail.from.default", service.getEmailConfig().getDefaultFrom()); String fromName = service.getEmailConfig().getFromName(); if (StringUtils.isEmpty(fromName)) { fromName = Messages.getInstance().getString("schedulerEmailFromName"); } props.put("mail.from.name", fromName); props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug())); Session session; if (service.getEmailConfig().isAuthenticate()) { props.put("mail.userid", service.getEmailConfig().getUserId()); props.put("mail.password", service.getEmailConfig().getPassword()); Authenticator authenticator = new EmailAuthenticator(); session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // debugging is on if either component (xaction) or email config debug is on if (service.getEmailConfig().isDebug() || ComponentBase.debug) { session.setDebug(true); } // construct the message MimeMessage msg = new MimeMessage(session); if (from != null) { msg.setFrom(new InternetAddress(from)); } else { // There should be no way to get here error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } EmailAttachment[] emailAttachments = emailAction.getAttachments(); if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) { msg.setText(messagePlain, LocaleHelper.getSystemEncoding()); } else if (emailAttachments.length == 0) { if (messagePlain != null) { msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ } if (messageHtml != null) { msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ } } else { // need to create a multi-part message... // create the Multipart and add its parts to it Multipart multipart = new MimeMultipart(); // create and fill the first message part if (messageHtml != null) { // create and fill the first message part MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(htmlBodyPart); } if (messagePlain != null) { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(textBodyPart); } for (EmailAttachment element : emailAttachments) { IPentahoStreamSource source = element.getContent(); if (source == null) { error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$ return false; } DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source); String attachmentName = element.getName(); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$ } // create the second message part MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // attach the file to the message attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(attachmentName); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$ dataSource.getName())); } multipart.addBodyPart(attachmentBodyPart); } // add the Multipart to the message msg.setContent(multipart); } msg.setHeader("X-Mailer", EmailComponent.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$ } return true; // TODO: persist the content set for a while... } catch (SendFailedException e) { error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$ /* * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof * MessagingException) { sfe = (MessagingException) ne; * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe); * //$NON-NLS-1$ } */ } catch (AuthenticationFailedException e) { error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$ } catch (Throwable e) { error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$ } return false; }
From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java
public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) { // Retrieve SMTP server information String host = getSmtpHost();/* ww w .j a v a2 s. c o m*/ boolean isSmtpAuthentication = isSmtpAuthentication(); int smtpPort = getSmtpPort(); String smtpUser = getSmtpUser(); String smtpPwd = getSmtpPwd(); boolean isSmtpDebug = isSmtpDebug(); List<String> emailErrors = new ArrayList<String>(); if (emails.size() > 0) { // Corps et sujet du message String subject = getString("infoLetter.emailSubject") + ilp.getName(); // Email du publieur String from = getUserDetail().geteMail(); // create some properties and get the default Session Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication)); Session session = Session.getInstance(props, null); session.setDebug(isSmtpDebug); // print on the console all SMTP messages. SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "subject = " + subject); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "from = " + from); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host= " + host); try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, CharEncoding.UTF_8); ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId()); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg, I18NHelper.defaultLanguage); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (SimpleDocument content : contents) { AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(), content.getLanguage()); } mbp1.setDataHandler( new DataHandler(new ByteArrayDataSource( replaceFileServerWithLocal( IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server), MimeTypes.HTML_MIME_TYPE))); IOUtils.closeQuietly(buffer); // Fichiers joints WAPrimaryKey publiPK = ilp.getPK(); publiPK.setComponentName(getComponentId()); publiPK.setSpace(getSpaceId()); // create the Multipart and its parts to it String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related"); Multipart mp = new MimeMultipart(mimeMultipart); mp.addBodyPart(mbp1); // Images jointes List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null); for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); // For Displaying images in the mail mbp2.setFileName(attachment.getFilename()); mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } // Fichiers joints fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null); if (!fichiers.isEmpty()) { for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(attachment.getFilename()); // For Displaying images in the mail mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // create a Transport connection (TCP) Transport transport = session.getTransport("smtp"); InternetAddress[] address = new InternetAddress[1]; for (String email : emails) { try { address[0] = new InternetAddress(email); msg.setRecipients(Message.RecipientType.TO, address); // add Transport Listener to the transport connection. if (isSmtpAuthentication) { SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser); transport.connect(host, smtpPort, smtpUser, smtpPwd); msg.saveChanges(); } else { transport.connect(); } transport.sendMessage(msg, address); } catch (Exception ex) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "Email = " + email, new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, ex.getMessage(), ex)); emailErrors.add(email); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.EX_IGNORED", "ClosingTransport", e); } } } } } catch (Exception e) { throw new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, e.getMessage(), e); } } return emailErrors.toArray(new String[emailErrors.size()]); }
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 ww w . j ava 2 s .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:com.glaf.mail.MailSenderImpl.java
public void send(JavaMailSender javaMailSender, MailMessage mailMessage) throws Exception { if (StringUtils.isEmpty(mailMessage.getMessageId())) { mailMessage.setMessageId(UUID32.getUUID()); }/*from ww w. j av a2 s . c o m*/ mailHelper = new MxMailHelper(); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true); if (StringUtils.isNotEmpty(mailMessage.getFrom())) { messageHelper.setFrom(mailMessage.getFrom()); mailFrom = mailMessage.getFrom(); } else { if (StringUtils.isEmpty(mailFrom)) { mailFrom = MailProperties.getString("mail.mailFrom"); } messageHelper.setFrom(mailFrom); } logger.debug("mailFrom:" + mailFrom); if (mailMessage.getTo() != null) { messageHelper.setTo(mailMessage.getTo()); } if (mailMessage.getCc() != null) { messageHelper.setCc(mailMessage.getCc()); } if (mailMessage.getBcc() != null) { messageHelper.setBcc(mailMessage.getBcc()); } if (mailMessage.getReplyTo() != null) { messageHelper.setReplyTo(mailMessage.getReplyTo()); } String mailSubject = mailMessage.getSubject(); if (mailSubject == null) { mailSubject = ""; } if (mailSubject != null) { // mailSubject = MimeUtility.encodeText(new // String(mailSubject.getBytes(), encoding), encoding, "B"); mailSubject = MimeUtility.encodeWord(mailSubject); } mimeMessage.setSubject(mailSubject); Map<String, Object> dataMap = mailMessage.getDataMap(); if (dataMap == null) { dataMap = new java.util.HashMap<String, Object>(); } String serviceUrl = SystemConfig.getServiceUrl(); logger.debug("mailSubject:" + mailSubject); logger.debug("serviceUrl:" + serviceUrl); if (serviceUrl != null) { String loginUrl = serviceUrl + "/mx/login"; String mainUrl = serviceUrl + "/mx/main"; logger.debug("loginUrl:" + loginUrl); dataMap.put("loginUrl", loginUrl); dataMap.put("mainUrl", mainUrl); } mailMessage.setDataMap(dataMap); if (StringUtils.isEmpty(mailMessage.getContent())) { Template template = TemplateContainer.getContainer().getTemplate(mailMessage.getTemplateId()); if (template != null) { String templateType = template.getTemplateType(); logger.debug("templateType:" + templateType); // logger.debug("content:" + template.getContent()); if (StringUtils.equals(templateType, "eml")) { if (template.getContent() != null) { Mail m = mailHelper.getMail(template.getContent().getBytes()); String content = m.getContent(); if (StringUtils.isNotEmpty(content)) { template.setContent(content); try { Writer writer = new StringWriter(); TemplateUtils.evaluate(mailMessage.getTemplateId(), dataMap, writer); String text = writer.toString(); writer.close(); writer = null; mailMessage.setContent(text); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } } } else { try { String text = TemplateUtils.process(dataMap, template.getContent()); mailMessage.setContent(text); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } } } if (StringUtils.isNotEmpty(mailMessage.getContent())) { String text = mailMessage.getContent(); if (StringUtils.isNotEmpty(callbackUrl)) { String href = callbackUrl + "?messageId=" + mailMessage.getMessageId(); text = mailHelper.embedCallbackScript(text, href); mailMessage.setContent(text); logger.debug(text); messageHelper.setText(text, true); } messageHelper.setText(text, true); } logger.debug("mail body:" + mailMessage.getContent()); Collection<Object> files = mailMessage.getFiles(); if (files != null && !files.isEmpty()) { Iterator<Object> iterator = files.iterator(); while (iterator.hasNext()) { Object object = iterator.next(); if (object instanceof java.io.File) { java.io.File file = (java.io.File) object; FileSystemResource resource = new FileSystemResource(file); String name = file.getName(); name = MailTools.chineseStringToAscii(name); messageHelper.addAttachment(name, resource); logger.debug("add attachment:" + name); } else if (object instanceof DataSource) { DataSource dataSource = (DataSource) object; String name = dataSource.getName(); name = MailTools.chineseStringToAscii(name); messageHelper.addAttachment(name, dataSource); logger.debug("add attachment:" + name); } else if (object instanceof DataFile) { DataFile dataFile = (DataFile) object; if (StringUtils.isNotEmpty(dataFile.getFilename())) { String name = dataFile.getFilename(); name = MailTools.chineseStringToAscii(name); InputStreamSource inputStreamSource = new MxMailInputSource(dataFile); messageHelper.addAttachment(name, inputStreamSource); logger.debug("add attachment:" + name); } } } } mimeMessage.setSentDate(new java.util.Date()); javaMailSender.send(mimeMessage); logger.info("-----------------------------------------"); logger.info("????"); logger.info("-----------------------------------------"); }