List of usage examples for javax.mail.internet MimeMessage setRecipients
public void setRecipients(Message.RecipientType type, String addresses) throws MessagingException
From source file:com.netspective.commons.message.SendMail.java
public void send(ValueContext vc, Map bodyTemplateVars) throws IOException, AddressException, MessagingException, SendMailNoFromAddressException, SendMailNoRecipientsException { if (from == null) throw new SendMailNoFromAddressException("No FROM address provided."); if (to == null && cc == null && bcc == null) throw new SendMailNoRecipientsException("No TO, CC, or BCC addresses provided."); Properties props = System.getProperties(); props.put("mail.smtp.host", host.getTextValue(vc)); Session mailSession = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(mailSession); if (headers != null) { List headersList = headers.getHeaders(); for (int i = 0; i < headersList.size(); i++) { Header header = (Header) headersList.get(i); message.setHeader(header.getName(), header.getValue().getTextValue(vc)); }// w w w . j av a 2 s. c o m } message.setFrom(new InternetAddress(from.getTextValue(vc))); if (replyTo != null) message.setReplyTo(getAddresses(replyTo.getValue(vc))); if (to != null) message.setRecipients(Message.RecipientType.TO, getAddresses(to.getValue(vc))); if (cc != null) message.setRecipients(Message.RecipientType.CC, getAddresses(cc.getValue(vc))); if (bcc != null) message.setRecipients(Message.RecipientType.BCC, getAddresses(bcc.getValue(vc))); if (subject != null) message.setSubject(subject.getTextValue(vc)); if (body != null) { StringWriter messageText = new StringWriter(); body.process(messageText, vc, bodyTemplateVars); message.setText(messageText.toString()); } Transport.send(message); }
From source file:com.commoncoupon.mail.EmailProcessor.java
public Integer call() throws Exception { MimeMessage message = new MimeMessage(getSession()); try {/*from w w w .j a v a 2 s.c o m*/ if (from != null && (from != null && from.trim() != "")) { InternetAddress sentFrom = new InternetAddress(from); message.setFrom(sentFrom); if (log.isDebugEnabled()) log.debug("Email sent from: " + sentFrom); } if (to != null && to.length > 0) { InternetAddress[] sendTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress((String) to[i]); if (log.isDebugEnabled()) log.debug("Sending e-mail to: " + to[i]); } message.setRecipients(Message.RecipientType.TO, sendTo); } if (cc != null && cc.length > 0) { InternetAddress[] copyTo = new InternetAddress[cc.length]; for (int i = 0; i < cc.length; i++) { copyTo[i] = new InternetAddress((String) cc[i]); if (log.isDebugEnabled()) log.debug("Copying e-mail to: " + cc[i]); } message.setRecipients(Message.RecipientType.CC, copyTo); } message.setSentDate(new Date()); message.setSubject(subject); message.setContent(content, mimeType); Transport.send(message); } catch (Exception e) { log.error("Failed to send email.", e); return (1); } return (0); }
From source file:org.grouter.common.mail.MailHandler.java
/** * @param mimeMessage//w ww . ja v a2 s . c o m * @throws UnsupportedEncodingException * @throws MessagingException */ private void createHeader(MimeMessage mimeMessage, MailDto mailDto) throws UnsupportedEncodingException, MessagingException { //from InternetAddress fromAddress = new InternetAddress(mailDto.getFrom()); fromAddress.setPersonal(mailDto.getSenderNote(), ENCODING); mimeMessage.setSender(fromAddress); //to List<String> senders = mailDto.getTo(); InternetAddress[] toAddress = getRecipients(senders); List<String> sendersCc = mailDto.getCc(); InternetAddress[] toAddressCc = getRecipients(sendersCc); List<String> sendersBcc = mailDto.getBcc(); InternetAddress[] toAddressBcc = getRecipients(sendersBcc); mimeMessage.setRecipients(Message.RecipientType.TO, toAddress); mimeMessage.setRecipients(Message.RecipientType.CC, toAddressCc); mimeMessage.setRecipients(Message.RecipientType.BCC, toAddressBcc); //subject mimeMessage.setSubject(mailDto.getSubject(), ENCODING); //sent date mimeMessage.setSentDate(new Date()); }
From source file:edu.cornell.mannlib.vitro.webapp.controller.MailUsersServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { VitroRequest vreq = new VitroRequest(request); String confirmpage = "/confirmUserMail.jsp"; String errpage = "/contact_err.jsp"; String status = null; // holds the error status if (!FreemarkerEmailFactory.isConfigured(vreq)) { status = "This application has not yet been configured to send mail. " + "Email properties must be specified in the configuration properties file."; response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status); return;//from w w w . j av a 2 s. c om } String SPAM_MESSAGE = "Your message was flagged as spam."; boolean probablySpam = false; String spamReason = ""; String originalReferer = (String) request.getSession().getAttribute("commentsFormReferer"); request.getSession().removeAttribute("commentsFormReferer"); if (originalReferer == null) { originalReferer = "none"; // (the following does not support cookie-less browsing:) // probablySpam = true; // status = SPAM_MESSAGE; } else { String referer = request.getHeader("Referer"); //Review how spam works? /*if (referer.indexOf("comments")<0 && referer.indexOf("correction")<0) { probablySpam=true; status = SPAM_MESSAGE ; spamReason = "The form was not submitted from the Contact Us or Corrections page."; }*/ } String formType = vreq.getParameter("DeliveryType"); List<String> deliverToArray = null; int recipientCount = 0; String deliveryfrom = null; // get Individuals that the User mayEditAs deliverToArray = getEmailsForAllUserAccounts(vreq); //Removed all form type stuff b/c recipients pre-configured recipientCount = (deliverToArray == null) ? 0 : deliverToArray.size(); if (recipientCount == 0) { //log.error("recipientCount is 0 when DeliveryType specified as \""+formType+"\""); throw new Error("To establish the Contact Us mail capability the system administrators must " + "specify at least one email address in the current portal."); } // obtain passed in form data with a simple trim on the values String webusername = vreq.getParameter("webusername");// Null.trim(); will give you an exception String webuseremail = vreq.getParameter("webuseremail");//.trim(); String comments = vreq.getParameter("s34gfd88p9x1"); //what does this string signify? //webusername = "hjk54"; //webuseremail = "hjk54@cornell.edu"; //comments = "following are comments"; webusername = webusername.trim(); deliveryfrom = webuseremail; comments = comments.trim(); //Removed spam filtering code StringBuffer msgBuf = new StringBuffer(); // contains the intro copy for the body of the email message String lineSeparator = System.getProperty("line.separator"); // \r\n on windows, \n on unix // from MyLibrary msgBuf.setLength(0); //msgBuf.append("Content-Type: text/html; charset='us-ascii'" + lineSeparator); msgBuf.append("<html>" + lineSeparator); msgBuf.append("<head>" + lineSeparator); msgBuf.append("<style>a {text-decoration: none}</style>" + lineSeparator); msgBuf.append("<title>" + deliveryfrom + "</title>" + lineSeparator); msgBuf.append("</head>" + lineSeparator); msgBuf.append("<body>" + lineSeparator); msgBuf.append("<h4>" + deliveryfrom + "</h4>" + lineSeparator); msgBuf.append("<h4>From: " + webusername + " (" + webuseremail + ")" + " at IP address " + request.getRemoteAddr() + "</h4>" + lineSeparator); //Don't need any 'likely viewing page' portion to be emailed out to the others msgBuf.append(lineSeparator + "</i></p><h3>Comments:</h3>" + lineSeparator); if (comments == null || comments.equals("")) { msgBuf.append("<p>BLANK MESSAGE</p>"); } else { msgBuf.append("<p>" + comments + "</p>"); } msgBuf.append("</body>" + lineSeparator); msgBuf.append("</html>" + lineSeparator); String msgText = msgBuf.toString(); Calendar cal = Calendar.getInstance(); /* outFile.println("<hr/>"); outFile.println(); outFile.println("<p>"+cal.getTime()+"</p>"); outFile.println(); if (probablySpam) { outFile.println("<p>REJECTED - SPAM</p>"); outFile.println("<p>"+spamReason+"</p>"); outFile.println(); } outFile.print( msgText ); outFile.println(); outFile.println(); outFile.flush(); // outFile.close(); */ Session s = FreemarkerEmailFactory.getEmailSession(vreq); //s.setDebug(true); try { // Construct the message MimeMessage msg = new MimeMessage(s); log.debug("trying to send message from servlet"); // Set the from address msg.setFrom(new InternetAddress(webuseremail)); // Set the recipient address if (recipientCount > 0) { InternetAddress[] address = new InternetAddress[recipientCount]; for (int i = 0; i < recipientCount; i++) { address[i] = new InternetAddress(deliverToArray.get(i)); } msg.setRecipients(Message.RecipientType.TO, address); } // Set the subject and text msg.setSubject(deliveryfrom); // add the multipart to the message msg.setContent(msgText, "text/html"); // set the Date: header msg.setSentDate(new Date()); log.debug("sending from servlet"); //if (!probablySpam) Transport.send(msg); // try to send the message via smtp - catch error exceptions } catch (AddressException e) { status = "Please supply a valid email address."; log.debug("Error - status is " + status); } catch (SendFailedException e) { status = "The system was unable to deliver your mail. Please try again later. [SEND FAILED]"; log.error("Error - status is " + status); } catch (MessagingException e) { status = "The system was unable to deliver your mail. Please try again later. [MESSAGING]"; log.error("Error - status is " + status, e); } //outFile.flush(); //outFile.close(); // Redirect to the appropriate confirmation page if (status == null && !probablySpam) { // message was sent successfully response.sendRedirect("test?bodyJsp=" + confirmpage); } else { // exception occurred response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status); } }
From source file:org.opens.emailsender.EmailSender.java
/** * * @param emailFrom/*from w w w .jav a 2 s . c om*/ * @param emailToSet * @param emailBccSet (can be null) * @param replyTo (can be null) * @param emailSubject * @param emailContent */ public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo, String emailSubject, String emailContent) { boolean debug = false; // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // create some properties and get the default Session Session session = Session.getInstance(props); session.setDebug(debug); try { Transport t = session.getTransport("smtp"); t.connect(smtpHost, userName, password); // create a message MimeMessage msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom; try { // Used default from address is passed one is null or empty or // blank addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom) : new InternetAddress(from); msg.setFrom(addressFrom); Address[] recipients = new InternetAddress[emailToSet.size()]; int i = 0; for (String emailTo : emailToSet) { recipients[i] = new InternetAddress(emailTo); i++; } msg.setRecipients(Message.RecipientType.TO, recipients); if (CollectionUtils.isNotEmpty(emailBccSet)) { Address[] bccRecipients = new InternetAddress[emailBccSet.size()]; i = 0; for (String emailBcc : emailBccSet) { bccRecipients[i] = new InternetAddress(emailBcc); i++; } msg.setRecipients(Message.RecipientType.BCC, bccRecipients); } if (StringUtils.isNotBlank(replyTo)) { Address[] replyToRecipients = { new InternetAddress(replyTo) }; msg.setReplyTo(replyToRecipients); } // Setting the Subject msg.setSubject(emailSubject, CHARSET_KEY); // Setting content and charset (warning: both declarations of // charset are needed) msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY); LOGGER.error("emailContent " + emailContent); msg.setContent(emailContent, FULL_CHARSET_KEY); try { LOGGER.debug("emailContent from message object " + msg.getContent().toString()); } catch (IOException ex) { LOGGER.error(ex.getMessage()); } catch (MessagingException ex) { LOGGER.error(ex.getMessage()); } for (Address addr : msg.getAllRecipients()) { LOGGER.error("addr " + addr); } t.sendMessage(msg, msg.getAllRecipients()); } catch (AddressException ex) { LOGGER.warn(ex.getMessage()); } } catch (NoSuchProviderException e) { LOGGER.warn(e.getMessage()); } catch (MessagingException e) { LOGGER.warn(e.getMessage()); } }
From source file:org.asqatasun.emailsender.EmailSender.java
/** * * @param emailFrom//from w w w .j a v a 2s.c om * @param emailToSet * @param emailBccSet (can be null) * @param replyTo (can be null) * @param emailSubject * @param emailContent */ public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo, String emailSubject, String emailContent) { boolean debug = false; // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // create some properties and get the default Session Session session = Session.getInstance(props); session.setDebug(debug); try { Transport t = session.getTransport("smtp"); t.connect(smtpHost, userName, password); // create a message MimeMessage msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom; try { // Used default from address is passed one is null or empty or // blank addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom) : new InternetAddress(from); msg.setFrom(addressFrom); Address[] recipients = new InternetAddress[emailToSet.size()]; int i = 0; for (String emailTo : emailToSet) { recipients[i] = new InternetAddress(emailTo); i++; } msg.setRecipients(Message.RecipientType.TO, recipients); if (CollectionUtils.isNotEmpty(emailBccSet)) { Address[] bccRecipients = new InternetAddress[emailBccSet.size()]; i = 0; for (String emailBcc : emailBccSet) { bccRecipients[i] = new InternetAddress(emailBcc); i++; } msg.setRecipients(Message.RecipientType.BCC, bccRecipients); } if (StringUtils.isNotBlank(replyTo)) { Address[] replyToRecipients = { new InternetAddress(replyTo) }; msg.setReplyTo(replyToRecipients); } // Setting the Subject msg.setSubject(emailSubject, CHARSET_KEY); // Setting content and charset (warning: both declarations of // charset are needed) msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY); LOGGER.debug("emailContent " + emailContent); msg.setContent(emailContent, FULL_CHARSET_KEY); try { LOGGER.debug("emailContent from message object " + msg.getContent().toString()); } catch (IOException ex) { LOGGER.error(ex.getMessage()); } catch (MessagingException ex) { LOGGER.error(ex.getMessage()); } for (Address addr : msg.getAllRecipients()) { LOGGER.debug("addr " + addr); } t.sendMessage(msg, msg.getAllRecipients()); } catch (AddressException ex) { LOGGER.warn("AddressException " + ex.getMessage()); LOGGER.warn("AddressException " + ex.getStackTrace()); } } catch (NoSuchProviderException e) { LOGGER.warn("NoSuchProviderException " + e.getMessage()); LOGGER.warn("NoSuchProviderException " + e.getStackTrace()); } catch (MessagingException e) { LOGGER.warn("MessagingException " + e.getMessage()); LOGGER.warn("MessagingException " + e.getStackTrace()); } }
From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; message = "Some of the appliances in your house are running inefficient." + "\n" + "Kindly check or replace your appliance " + "\n" + "Check the attachment for details or visit your account"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/*from ww w. ja v a2 s . com*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Energy Board"); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(message); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(name_attach.getText() + ".png"); multipart.addBodyPart(messageBodyPart); mimeMessage.setContent(multipart); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); System.out.println("sent"); transport.close(); } catch (MessagingException me) { } }
From source file:org.nuxeo.ecm.user.invite.UserInvitationComponent.java
protected void generateMail(String destination, String copy, String title, String content) throws NamingException, MessagingException { InitialContext ic = new InitialContext(); Session session = (Session) ic.lookup(getJavaMailJndiName()); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination, false)); if (!isBlank(copy)) { msg.addRecipient(Message.RecipientType.CC, new InternetAddress(copy, false)); }/*from ww w . j a v a 2 s. c o m*/ msg.setSubject(title, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content, "text/html; charset=utf-8"); Transport.send(msg); }
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;/* ww w . j a v a 2 s .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.j2free.email.EmailService.java
private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body, ContentType contentType, Priority priority, boolean ccSender) throws AddressException, MessagingException, RejectedExecutionException { MimeMessage message = new MimeMessage(session); message.setFrom(from);//from w w w . j ava 2 s . c om message.setRecipients(Message.RecipientType.TO, recipients); for (Map.Entry<String, String> header : headers.entrySet()) message.setHeader(header.getKey(), header.getValue()); // CC the sender if they want if (ccSender) message.addRecipient(Message.RecipientType.CC, from); message.setReplyTo(new InternetAddress[] { from }); message.setSubject(subject); message.setSentDate(new Date()); if (contentType == ContentType.PLAIN) { // Just set the body as plain text message.setText(body, "UTF-8"); } else { MimeMultipart multipart = new MimeMultipart("alternative"); // Create the text part MimeBodyPart text = new MimeBodyPart(); text.setText(new HtmlFilter().filterForEmail(body), "UTF-8"); // Add the text part multipart.addBodyPart(text); // Create the HTML portion MimeBodyPart html = new MimeBodyPart(); html.setContent(body, ContentType.HTML.toString()); // Add the HTML portion multipart.addBodyPart(html); // set the message content message.setContent(multipart); } enqueue(message, priority); }