List of usage examples for javax.mail.internet MimeMessage setHeader
@Override public void setHeader(String name, String value) throws MessagingException
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;//w ww .j a v a 2s. c o m } /* * 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:org.pentaho.platform.plugin.services.email.EmailService.java
/** * Tests the provided email configuration by sending a test email. This will just indicate that the server * configuration is correct and a test email was successfully sent. It does not test the destination address. * //from w ww . j av a 2s. c o m * @param emailConfig * the email configuration to test * @throws Exception * indicates an error running the test (as in an invalid configuration) */ public String sendEmailTest(final IEmailConfiguration emailConfig) { final Properties emailProperties = new Properties(); emailProperties.setProperty("mail.smtp.host", emailConfig.getSmtpHost()); emailProperties.setProperty("mail.smtp.port", ObjectUtils.toString(emailConfig.getSmtpPort())); emailProperties.setProperty("mail.transport.protocol", emailConfig.getSmtpProtocol()); emailProperties.setProperty("mail.smtp.starttls.enable", ObjectUtils.toString(emailConfig.isUseStartTls())); emailProperties.setProperty("mail.smtp.auth", ObjectUtils.toString(emailConfig.isAuthenticate())); emailProperties.setProperty("mail.smtp.ssl", ObjectUtils.toString(emailConfig.isUseSsl())); emailProperties.setProperty("mail.debug", ObjectUtils.toString(emailConfig.isDebug())); Session session = null; if (emailConfig.isAuthenticate()) { Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailConfig.getUserId(), emailConfig.getPassword()); } }; session = Session.getInstance(emailProperties, authenticator); } else { session = Session.getInstance(emailProperties); } String sendEmailMessage = ""; try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(emailConfig.getDefaultFrom(), emailConfig.getFromName())); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailConfig.getDefaultFrom())); msg.setSubject(messages.getString("EmailService.SUBJECT")); msg.setText(messages.getString("EmailService.MESSAGE")); msg.setHeader("X-Mailer", "smtpsend"); msg.setSentDate(new Date()); Transport.send(msg); sendEmailMessage = "EmailTester.SUCESS"; } catch (Exception e) { logger.error(messages.getString("EmailService.NOT_CONFIGURED"), e); sendEmailMessage = "EmailTester.FAIL"; } return sendEmailMessage; }
From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java
public boolean send() { String cc = null;//from w w w .j a v a 2 s . c o m String bcc = null; String from = props.getProperty("mail.from.default"); String to = props.getProperty("to"); 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 { // Get a Session object Session session; if (authenticate) { Authenticator authenticator = new EmailAuthenticator(); 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); } // construct the message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (from != null) { msg.setFrom(new InternetAddress(from)); } 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()); } if (body != null) { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(textBodyPart); } // need to create a multi-part message... // create the Multipart and add its parts to it // create and fill the first message part IPentahoStreamSource source = attachment; if (source == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source); // create the second message part MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // attach the file to the message attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(attachmentName); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; // TODO: persist the content set for a while... } 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:org.pentaho.platform.scheduler2.email.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 www . j av a 2 s. com*/ // 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); } // construct the message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); 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()); } 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); 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: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 w w .j a va2 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:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java
/** * Perform the primary function of this component, this is, to execute. This method will be invoked immediately following a successful validate(). * <p/>/*from w w w .j a va 2 s .c om*/ * This method has 2 ways of working: * <p/> * 1. You supply a mimeMessage: That mimeMessage will be sent; * Optionally, contents will be added as attachment and the original * mimeMessage will be encapsulated under a multipart/mixed * <p/> * <p/> * 2. You supply a messageHtml and/or a messageText. A new mimemessage will be * built. If you supply both, a multipart/alternative will be used. After that * attachments will be included * * @return true if successful execution * @throws Exception */ public boolean execute() throws Exception { try { // Get the session object final Session session = buildSession(); // Create the message final MimeMessage msg = new MimeMessage(session); // From, to, etc. applyMessageHeaders(msg); // Get main message multipart final Multipart multipartBody = getMultipartBody(session); // Process attachments final Multipart mainMultiPart = processAttachments(multipartBody); msg.setContent(mainMultiPart); // Send it msg.setHeader("X-Mailer", MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { log.error(Messages.getInstance().getString("ReportPlugin.emailSendFailed")); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { log.error(Messages.getInstance().getString("ReportPlugin.emailAuthenticationFailed")); //$NON-NLS-1$ } return false; }
From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java
public void handleMessage(Message email) throws AddressException, UnsupportedEncodingException, SendFailedException, MessagingException, IOException { String fromAddress = email.getHeader(Message.Field.FROM); if (fromAddress == null) { throw new MessagingException("Unable to send without a 'from' address."); }/*from w ww . ja v a 2 s . c o m*/ // transform to a MimeMessage ArrayList<String> invalids = new ArrayList<String>(); // convert and validate the 'from' address InternetAddress from = new InternetAddress(fromAddress, true); // convert and validate reply to addresses String replyTos = email.getHeader(EmailMessage.Field.REPLY_TO); InternetAddress[] replyTo = emails2Internets(replyTos, invalids); // convert and validate the 'to' addresses String tos = email.getHeader(Message.Field.TO); InternetAddress[] to = emails2Internets(tos, invalids); // convert and validate 'cc' addresses String ccs = email.getHeader(EmailMessage.Field.CC); InternetAddress[] cc = emails2Internets(ccs, invalids); // convert and validate 'bcc' addresses String bccs = email.getHeader(EmailMessage.Field.BCC); InternetAddress[] bcc = emails2Internets(bccs, invalids); int totalRcpts = to.length + cc.length + bcc.length; if (totalRcpts == 0) { throw new MessagingException("No recipients to send to."); } MimeMessage mimeMsg = new MimeMessage(session); mimeMsg.setFrom(from); mimeMsg.setReplyTo(replyTo); mimeMsg.setRecipients(RecipientType.TO, to); mimeMsg.setRecipients(RecipientType.CC, cc); mimeMsg.setRecipients(RecipientType.BCC, bcc); // add in any additional headers Map<String, String> headers = email.getHeaders(); if (headers != null && !headers.isEmpty()) { for (Entry<String, String> header : headers.entrySet()) { mimeMsg.setHeader(header.getKey(), header.getValue()); } } // add the content to the message List<Message> parts = email.getParts(); if (parts == null || parts.size() == 0) { setContent(mimeMsg, email); } else { // create a multipart container Multipart multipart = new MimeMultipart(); // create a body part for the message text MimeBodyPart msgBodyPart = new MimeBodyPart(); setContent(msgBodyPart, email); // add the message part to the container multipart.addBodyPart(msgBodyPart); // add attachments for (Message part : parts) { addPart(multipart, part); } // set the multipart container as the content of the message mimeMsg.setContent(multipart); } if (allowTransport) { // send Transport.send(mimeMsg); } else { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); mimeMsg.writeTo(output); String emailString = output.toString(); LOG.info(emailString); observable.notifyObservers(emailString); } catch (IOException e) { LOG.info("Transport disabled and unable to write message to log: " + e.getMessage(), e); } } }
From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java
@Override public void send(final MailToSend mail) { SmtpConfiguration smtpConfiguration = SmtpConfiguration.fromDefaultSettings(); MailAddress fromMailAddress = mail.getFrom(); Session session = getMailSession(smtpConfiguration); try {/* w w w. j ava 2s. c o m*/ InternetAddress fromAddress = fromMailAddress.getAuthorizedInternetAddress(); InternetAddress replyToAddress = null; List<InternetAddress[]> toAddresses = new ArrayList<>(); // Parsing destination address for compliance with RFC822. final Collection<ReceiverMailAddressSet> addressBatches = mail.getTo().getBatchedReceiversList(); for (ReceiverMailAddressSet addressBatch : addressBatches) { try { toAddresses.add(InternetAddress.parse(addressBatch.getEmailsSeparatedByComma(), false)); } catch (AddressException e) { SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE", "From = " + fromMailAddress + ", To = " + addressBatch.getEmailsSeparatedByComma(), e); } } try { if (mail.isReplyToRequired()) { replyToAddress = new InternetAddress(fromMailAddress.getEmail(), false); if (StringUtil.isDefined(fromMailAddress.getName())) { replyToAddress.setPersonal(fromMailAddress.getName(), Charsets.UTF_8.name()); } } } catch (AddressException e) { SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE", "ReplyTo = " + fromMailAddress + " is malformed.", e); } MimeMessage email = new MimeMessage(session); email.setFrom(fromAddress); if (replyToAddress != null) { email.setReplyTo(new InternetAddress[] { replyToAddress }); } email.setHeader("Precedence", "list"); email.setHeader("List-ID", fromAddress.getAddress()); email.setSentDate(new Date()); email.setSubject(mail.getSubject(), CharEncoding.UTF_8); mail.getContent().applyOn(email); // Sending. performSend(mail, smtpConfiguration, session, email, toAddresses); } catch (MessagingException | UnsupportedEncodingException e) { SilverLogger.getLogger(this).error(e.getMessage(), e); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.tizzit.util.mail.MailHelper.java
/** * Send an email in html-format in iso-8859-1-encoding * /* w w w . java 2 s. c o m*/ * @param subject the subject of the new mail * @param htmlMessage the content of the mail as html * @param alternativeTextMessage the content of the mail as text * @param from the sender-address * @param to the receiver-address * @param cc the address of the receiver of a copy of this mail * @param bcc the address of the receiver of a blind-copy of this mail */ public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from, String to, String cc, String bcc) { try { MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); if (cc != null && !cc.equals("")) msg.setRecipients(Message.RecipientType.CC, cc); if (bcc != null && !bcc.equals("")) msg.setRecipients(Message.RecipientType.BCC, bcc); msg.addRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "ISO8859_1"); msg.setSentDate(new Date()); MimeMultipart multiPart = new MimeMultipart("alternative"); MimeBodyPart htmlPart = new MimeBodyPart(); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(alternativeTextMessage, "ISO8859_1"); textPart.setHeader("MIME-Version", "1.0"); //textPart.setHeader("Content-Type", textPart.getContentType()); textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\""); htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\""); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\""); //htmlPart.setHeader("Content-Type", htmlPart.getContentType()); multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); multiPart.setSubType("alternative"); msg.setContent(multiPart); msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", multiPart.getContentType()); Transport.send(msg); } catch (Exception e) { log.error("Error sending html-mail: " + e.getLocalizedMessage()); } }
From source file:org.tizzit.util.mail.MailHelper.java
/** * Send an email in html-format in iso-8859-1-encoding * //from ww w. j ava2s. c om * @param subject the subject of the new mail * @param htmlMessage the content of the mail as html * @param alternativeTextMessage the content of the mail as text * @param from the sender-address * @param to the receiver-address * @param cc the address of the receiver of a copy of this mail * @param bcc the address of the receiver of a blind-copy of this mail */ public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from, String[] to, String[] cc, String[] bcc) { try { MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); if (cc != null && cc.length != 0) { for (int i = cc.length - 1; i >= 0; i--) { msg.addRecipients(Message.RecipientType.CC, cc[i]); } } if (bcc != null && bcc.length != 0) { for (int i = bcc.length - 1; i >= 0; i--) { msg.addRecipients(Message.RecipientType.BCC, bcc[i]); } } if (to != null && to.length != 0) { for (int i = to.length - 1; i >= 0; i--) { msg.addRecipients(Message.RecipientType.TO, to[i]); } } msg.setSubject(subject, "ISO8859_1"); msg.setSentDate(new Date()); MimeMultipart multiPart = new MimeMultipart("alternative"); MimeBodyPart htmlPart = new MimeBodyPart(); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(alternativeTextMessage, "ISO8859_1"); textPart.setHeader("MIME-Version", "1.0"); //textPart.setHeader("Content-Type", textPart.getContentType()); textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\""); htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\""); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\""); //htmlPart.setHeader("Content-Type", htmlPart.getContentType()); multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); multiPart.setSubType("alternative"); msg.setContent(multiPart); msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", multiPart.getContentType()); Transport.send(msg); } catch (Exception e) { log.error("Error sending html-mail: " + e.getLocalizedMessage()); } }