List of usage examples for org.apache.commons.mail HtmlEmail HtmlEmail
HtmlEmail
From source file:com.duroty.application.mail.manager.SendManager.java
/** * DOCUMENT ME!//ww w .ja v a 2 s . co m * * @param hsession DOCUMENT ME! * @param session DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param identity DOCUMENT ME! * @param to DOCUMENT ME! * @param cc DOCUMENT ME! * @param bcc DOCUMENT ME! * @param subject DOCUMENT ME! * @param body DOCUMENT ME! * @param attachments DOCUMENT ME! * @param isHtml DOCUMENT ME! * @param charset DOCUMENT ME! * @param headers DOCUMENT ME! * @param priority DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public void send(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint, String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml, String charset, InternetHeaders headers, String priority) throws MailException { try { if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } if ((body == null) || body.trim().equals("")) { body = " "; } Email email = null; if (isHtml) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charset); Users user = getUser(hsession, repositoryName); Identity identity = getIdentity(hsession, ideIdint, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null); InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null); InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _to); email.setTo(aux); } if ((_cc != null) && (_cc.length > 0)) { HashSet aux = new HashSet(_cc.length); Collections.addAll(aux, _cc); email.setCc(aux); } if ((_bcc != null) && (_bcc.length > 0)) { HashSet aux = new HashSet(_bcc.length); Collections.addAll(aux, _bcc); email.setBcc(aux); } email.setSubject(subject); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } if ((attachments != null) && (attachments.size() > 0)) { for (int i = 0; i < attachments.size(); i++) { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { MailPartObj obj = (MailPartObj) attachments.get(i); File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); if (email instanceof MultiPartEmail) { ((MultiPartEmail) email).attach(attachment); } } catch (Exception ex) { } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } } String mid = getId(); if (headers != null) { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) { email.addHeader(xheader.getName(), xheader.getValue()); } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) { email.addHeader(xheader.getName(), xheader.getValue()); } } } else { email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); } if (priority != null) { if (priority.equals("high")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "1"); } else if (priority.equals("low")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "5"); } } if (email instanceof HtmlEmail) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.saveSentMessage(mid, mime, user); Thread thread = new Thread(new SendMessageThread(email)); thread.start(); } catch (MailException e) { throw e; } catch (Exception e) { throw new MailException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:FacultyAdvisement.StudentRepository.java
public static void adminUpdate(DataSource ds, Student student, String oldUsername) throws SQLException { Connection conn = ds.getConnection(); if (conn == null) { throw new SQLException("conn is null; Can't get db connection"); }// ww w . j a va 2 s . co m try { PreparedStatement ps; ps = conn.prepareStatement( "Update STUDENT set EMAIL=?, FIRSTNAME=?, LASTNAME=?, MAJORCODE=?, PHONE=?, ADVISED=? where STUID=?"); ps.setString(1, student.getUsername()); ps.setString(2, student.getFirstName()); ps.setString(3, student.getLastName()); ps.setString(4, student.getMajorCode()); ps.setString(5, student.getPhoneNumber()); if (student.isAdvised()) { ps.setString(6, "true"); } else { ps.setString(6, "false"); } ps.setString(7, student.getId()); ps.executeUpdate(); ps = conn.prepareStatement("Update USERTABLE set USERNAME=? where USERNAME=?"); ps.setString(1, student.getUsername()); ps.setString(2, oldUsername); ps.executeUpdate(); ps = conn.prepareStatement("Update GROUPTABLE set USERNAME=? where USERNAME=?"); ps.setString(1, student.getUsername()); ps.setString(2, oldUsername); ps.executeUpdate(); if (student.isResetPassword()) { String newPassword = UUID.randomUUID().toString(); String encryptedPassword = SHA256Encrypt.encrypt(newPassword); ps = conn.prepareStatement("Update USERTABLE set PASSWORD=? where USERNAME=?"); ps.setString(1, encryptedPassword); ps.setString(2, student.getUsername()); ps.executeUpdate(); Email email = new HtmlEmail(); email.setHostName("smtp.googlemail.com"); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator("uco.faculty.advisement", "!@#$1234")); email.setSSLOnConnect(true); email.setFrom("uco.faculty.advisement@gmail.com"); email.setSubject("UCO Faculty Advisement Password Change"); email.setMsg("<font size=\"3\">An admin has resetted your password, your new password is \"" + newPassword + "\"." + "\n<p align=\"center\">UCO Faculty Advisement</p></font>"); email.addTo(student.getUsername()); email.send(); } } catch (EmailException ex) { Logger.getLogger(StudentRepository.class.getName()).log(Level.SEVERE, null, ex); } finally { conn.close(); } //students = (HashMap<String, StudentPOJO>) readAll(); // reload the updated info }
From source file:Email.CommonsEmail.java
/** * Envia email no formato HTML/*w ww.ja v a2 s .co m*/ * * @throws EmailException * @throws MalformedURLException */ private void enviaEmailFormatoHtml() throws EmailException, MalformedURLException, IOException, Exception { String para = "alessandropereirarezende@gmail.com;alessandrorezende@msn.com"; StringTokenizer stPara = new StringTokenizer(para, ";"); while (stPara.hasMoreTokens()) { HtmlEmail email = new HtmlEmail(); // adiciona uma imagem ao corpo da mensagem e retorna seu id URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif"); String cid = email.embed(url, "Apache logo"); System.out.println(cid); // configura a mensagem para o formato HTML File img = new File(Functions.getCurrentPath() + "web\\resources\\images\\facom.png"); StringBuilder msg = new StringBuilder(); msg.append("<html><body>"); msg.append("<img src=cid:").append(email.embed(img)).append(">"); msg.append("</body></html>"); // configure uma mensagem alternativa caso o servidor no suporte HTML email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML"); // o servidor SMTP para envio do e-mail email.setHostName("smtp.gmail.com"); // remetente email.setFrom(emailConfig.getEmail(), emailConfig.getNome()); email.setAuthentication(emailConfig.getUsuario(), emailConfig.getSenha()); email.setSmtpPort(emailConfig.getPorta()); email.setSSLOnConnect(emailConfig.getSsl()); //destinatrio //email.addTo("alessandropereirarezende@gmail.com", "Alessandro"); email.addTo(stPara.nextToken().trim()); // assunto do e-mail email.setSubject("Teste -> Html Email"); email.setHtmlMsg(msg.toString()); //conteudo do e-mail //email.setMsg("Teste de Email HTML utilizando commons-email"); // envia email email.send(); } }
From source file:br.ufg.reqweb.components.MailBean.java
public void sendMailToDiscente(final Requerimento requerimento) { Thread sender = new Thread() { @Override//ww w . j a v a2s . c om public void run() { try { Configuration templateConf = new Configuration(); templateConf.setObjectWrapper(new DefaultObjectWrapper()); templateConf.setDefaultEncoding("UTF-8"); templateConf.setDirectoryForTemplateLoading(new File(context.getRealPath("/reports/mail"))); Map objectRoot = new HashMap(); objectRoot.put("TITULO", LocaleBean.getDefaultMessageBundle().getString("appTitle")); objectRoot.put("DISCENTE", LocaleBean.getDefaultMessageBundle().getString("discente")); objectRoot.put("REQUERIMENTO", LocaleBean.getDefaultMessageBundle().getString("requerimento")); objectRoot.put("STATUS", LocaleBean.getDefaultMessageBundle().getString("status")); objectRoot.put("ATENDENTE", LocaleBean.getDefaultMessageBundle().getString("atendente")); objectRoot.put("OBSERVACAO", LocaleBean.getDefaultMessageBundle().getString("observacao")); objectRoot.put("matricula", requerimento.getDiscente().getMatricula()); objectRoot.put("discente", requerimento.getDiscente().getNome()); objectRoot.put("tipoRequerimento", LocaleBean.getDefaultMessageBundle() .getString(requerimento.getTipoRequerimento().getTipo())); objectRoot.put("status", LocaleBean.getDefaultMessageBundle().getString(requerimento.getStatus().getStatus())); objectRoot.put("atendente", requerimento.getAtendimento().getAtendente().getNome()); objectRoot.put("observacao", requerimento.getAtendimento().getObservacao()); URL logo = new File(context.getRealPath("/resources/img/logo-mono-mini.png")).toURI().toURL(); Template template = templateConf.getTemplate("notificacao_discente.ftl"); Writer writer = new StringWriter(); HtmlEmail email = new HtmlEmail(); String logoId = email.embed(logo, "logo"); objectRoot.put("logo", logoId); template.process(objectRoot, writer); email.setHostName(configDao.getValue("mail.mailHost")); email.setSmtpPort(Integer.parseInt(configDao.getValue("mail.smtpPort"))); String mailSender = configDao.getValue("mail.mailSender"); String user = configDao.getValue("mail.mailUser"); String password = configDao.getValue("mail.mailPassword"); boolean useSSL = Boolean.parseBoolean(configDao.getValue("mail.useSSL")); email.setAuthenticator(new DefaultAuthenticator(user, password)); email.setSSLOnConnect(useSSL); email.setFrom(mailSender); email.addTo(requerimento.getDiscente().getEmail()); email.setSubject(LocaleBean.getDefaultMessageBundle().getString("subjectMail")); email.setHtmlMsg(writer.toString()); String alternativeMessage = String.format("%s\n%s: %s\n%s: %s\n%s: %s\n%s: %s", LocaleBean.getDefaultMessageBundle().getString("messageMail"), objectRoot.get("REQUERIMENTO"), objectRoot.get("tipoRequerimento"), objectRoot.get("STATUS"), objectRoot.get("status"), objectRoot.get("ATENDENTE"), objectRoot.get("atendente"), objectRoot.get("OBSERVACAO"), objectRoot.get("observacao")); email.setTextMsg(alternativeMessage); email.send(); System.out.println(String.format("message to discente:<%s: %s>", requerimento.getDiscente().getNome(), requerimento.getDiscente().getEmail())); } catch (EmailException | IOException | TemplateException e) { System.out.println("erro ao enviar email"); System.out.println(e); } } }; sender.start(); }
From source file:com.duroty.application.chat.manager.ChatManager.java
/** * DOCUMENT ME!//from www. j a v a2s .com * * @param hsession DOCUMENT ME! * @param userSender DOCUMENT ME! * @param userRecipient DOCUMENT ME! */ private void sendMail(Session hsession, javax.mail.Session msession, Users userSender, Users userRecipient, String message) { try { String sender = userSender.getUseUsername(); String recipient = userRecipient.getUseUsername(); Identity identitySender = getIdentity(hsession, userSender); Identity identityRecipient = getIdentity(hsession, userRecipient); HtmlEmail email = new HtmlEmail(); InternetAddress _from = new InternetAddress(identitySender.getIdeEmail(), identitySender.getIdeName()); InternetAddress _replyTo = new InternetAddress(identitySender.getIdeReplyTo(), identitySender.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(identityRecipient.getIdeEmail(), null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _from); Collections.addAll(aux, _to); email.setTo(aux); } email.setCharset(charset); email.setSubject("Chat " + sender + " >> " + recipient); email.setHtmlMsg(message); calendar.setTime(new Date()); String minute = "30"; if (calendar.get(Calendar.MINUTE) >= 30) { minute = "60"; } String value = String.valueOf(calendar.get(Calendar.YEAR)) + String.valueOf(calendar.get(Calendar.MONTH)) + String.valueOf(calendar.get(Calendar.DATE)) + String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)) + minute + String.valueOf(userSender.getUseIdint() + userRecipient.getUseIdint()); String reference = "<" + value + ".JavaMail.duroty@duroty" + ">"; email.addHeader(RFC2822Headers.IN_REPLY_TO, reference); email.addHeader(RFC2822Headers.REFERENCES, reference); email.addHeader("X-DBox", "CHAT"); Date now = new Date(); email.setSentDate(now); email.setMailSession(msession); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (controlQuota(hsession, userSender, size)) { //messageable.saveSentMessage(null, mime, userSender); Thread thread = new Thread(new SendMessageThread(email)); thread.start(); } } catch (UnsupportedEncodingException e) { } catch (MessagingException e) { } catch (EmailException e) { } catch (Exception e) { } }
From source file:br.com.itfox.beans.SendHtmlFormatedEmail.java
/** * * @param destinatario//from w w w . jav a 2 s.c o m * @param nome * @param assunto * @throws IOException */ public void sendingHtml(String destinatario, String nome, String assunto, int tipoId) throws IOException { try { // Create the email message HtmlEmail email = new HtmlEmail(); email.setHostName("mail.congressotrt15.com.br"); email.setSmtpPort(587); email.setAuthenticator(new DefaultAuthenticator("congresso@congressotrt15.com.br", "admtrt15xx")); email.setSSLOnConnect(false); //email.setTLS(true); email.setFrom("congresso@congressotrt15.com.br"); //email.setSubject("TestMail"); email.addTo(destinatario, nome); //email.setFrom("belchiorpalma@me.com", "Me"); email.setSubject(assunto); email.setSubject(MimeUtility.encodeText(assunto, "UTF-8", "B")); // embed the image and get the content id // URL url = linkBoleto;//new URL(linkBoleto); //String cid = email.embed(url, "Congresso TRT 15"); // set the html message //email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>"); String body = ""; body += this.htmlHead; if (tipoId == 1) { body += (this.bodyProfissional); } else if (tipoId == 2) { body += (this.bodyServidor); } else if (tipoId == 3) { body += (this.bodyMagistrado); } else if (tipoId == 4) { body += (this.bodyEstudante); } else { body += "Congresso TRT"; } // body+=("Faa Download do Boleto para pagamento: - <a href="+url+" target=\"_blank\">Clique Aqui para baixar o Boleto.</a>"); //body+="<img src=\"cid:"+cid+"\">"; body += ("</body></html>"); //email.setContent(body,CONTENT_TYPE); email.setHtmlMsg(body); //email.setHeaders(CONTENT_TYPE); //email.setHtmlMsg(body); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send(); } catch (EmailException ex) { // utils.Logger.getLogger("Erro ao enviar Email. "+tipoId+" - "+ex.toString(),tipoId); // utils.Logger.getLoggerPessoaFisica("Erro ao enviar email - sending html:"+ex.getMessage()); } }
From source file:com.manydesigns.mail.sender.DefaultMailSender.java
protected void send(Email emailBean) throws EmailException { logger.debug("Entering send(Email)"); org.apache.commons.mail.Email email; String textBody = emailBean.getTextBody(); String htmlBody = emailBean.getHtmlBody(); if (null == htmlBody) { if (emailBean.getAttachments().isEmpty()) { SimpleEmail simpleEmail = new SimpleEmail(); simpleEmail.setMsg(textBody); email = simpleEmail;/*from w ww . jav a 2 s .c o m*/ } else { MultiPartEmail multiPartEmail = new MultiPartEmail(); multiPartEmail.setMsg(textBody); for (Attachment attachment : emailBean.getAttachments()) { EmailAttachment emailAttachment = new EmailAttachment(); emailAttachment.setName(attachment.getName()); emailAttachment.setDisposition(attachment.getDisposition()); emailAttachment.setDescription(attachment.getDescription()); emailAttachment.setPath(attachment.getFilePath()); multiPartEmail.attach(emailAttachment); } email = multiPartEmail; } } else { HtmlEmail htmlEmail = new HtmlEmail(); htmlEmail.setHtmlMsg(htmlBody); if (textBody != null) { htmlEmail.setTextMsg(textBody); } for (Attachment attachment : emailBean.getAttachments()) { if (!attachment.isEmbedded()) { EmailAttachment emailAttachment = new EmailAttachment(); emailAttachment.setName(attachment.getName()); emailAttachment.setDisposition(attachment.getDisposition()); emailAttachment.setDescription(attachment.getDescription()); emailAttachment.setPath(attachment.getFilePath()); htmlEmail.attach(emailAttachment); } else { FileDataSource dataSource = new FileDataSource(new File(attachment.getFilePath())); htmlEmail.embed(dataSource, attachment.getName(), attachment.getContentId()); } } email = htmlEmail; } if (null != login && null != password) { email.setAuthenticator(new DefaultAuthenticator(login, password)); } email.setHostName(server); email.setSmtpPort(port); email.setSubject(emailBean.getSubject()); email.setFrom(emailBean.getFrom()); // hongliangpan add if ("smtp.163.com".equals(server)) { email.setFrom(login + "@163.com"); // email.setAuthenticator(new DefaultAuthenticator("test28797575", "1qa2ws3ed")); } for (Recipient recipient : emailBean.getRecipients()) { switch (recipient.getType()) { case TO: email.addTo(recipient.getAddress()); break; case CC: email.addCc(recipient.getAddress()); break; case BCC: email.addBcc(recipient.getAddress()); break; } } email.setSSL(ssl); email.setTLS(tls); email.setSslSmtpPort(port + ""); email.setCharset("UTF-8"); email.send(); logger.debug("Exiting send(Email)"); }
From source file:FacultyAdvisement.SignupBean.java
public String validateSignUp(ArrayList<Course> list, Appointment appointment) throws SQLException, IOException, EmailException { if (this.desiredCoureses == null || this.desiredCoureses.size() < 1) { FacesContext.getCurrentInstance().addMessage("desiredCourses:Submit", new FacesMessage(FacesMessage.SEVERITY_FATAL, "Please select some courses before confirming an appointment.", null)); }//from w w w .j a va 2s.co m for (int i = 0; i < list.size(); i++) { if (!this.checkRequsites(CourseRepository.readCourseWithRequisites(ds, list.get(i)))) { return null; } } try { DesiredCourseRepository.deleteFromAppointment(ds, this.appointment.aID); } catch (SQLException ex) { Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex); } DesiredCourseRepository.createDesiredCourses(ds, desiredCoureses, Long.toString(appointment.aID)); if (!this.edit) { try { Email email = new HtmlEmail(); email.setHostName("smtp.googlemail.com"); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator("uco.faculty.advisement", "!@#$1234")); email.setSSLOnConnect(true); email.setFrom("uco.faculty.advisement@gmail.com"); email.setSubject("UCO Faculty Advisement Appointmen Confirmation"); StringBuilder table = new StringBuilder(); table.append("<style>" + "td" + "{border-left:1px solid black;" + "border-top:1px solid black;}" + "table" + "{border-right:1px solid black;" + "border-bottom:1px solid black;}" + "</style>"); table.append( "<table><tr><td width=\"350\">Course Name</td><td width=\"350\">Course Subject</td><td width=\"350\">Course Number</td><td width=\"350\">Course Credits</td></tr> </table>"); for (int i = 0; i < this.desiredCoureses.size(); i++) { table.append("<tr><td width=\"350\">" + this.desiredCoureses.get(i).getName() + "</td>" + "<td width=\"350\">" + this.desiredCoureses.get(i).getSubject() + "</td>" + "<td width=\"350\">" + this.desiredCoureses.get(i).getNumber() + "</td>" + "<td width=\"350\">" + this.desiredCoureses.get(i).getCredits() + "</td></tr>" ); } email.setMsg("<p>Your appointment with your faculty advisor is at " + appointment.datetime + " on " + appointment.date + " . </p>" + "<p align=\"center\">Desired Courses</p>" + table.toString() + "<p align=\"center\">UCO Faculty Advisement</p></font>" ); email.addTo(username); email.send(); } catch (EmailException ex) { Logger.getLogger(VerificationBean.class.getName()).log(Level.SEVERE, null, ex); } } return "/customerFolder/profile.xhtml"; }
From source file:com.mirth.connect.connectors.smtp.SmtpDispatcher.java
@Override public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) { SmtpDispatcherProperties smtpDispatcherProperties = (SmtpDispatcherProperties) connectorProperties; String responseData = null;/*from w w w. j a v a 2s . c o m*/ String responseError = null; String responseStatusMessage = null; Status responseStatus = Status.QUEUED; String info = "From: " + smtpDispatcherProperties.getFrom() + " To: " + smtpDispatcherProperties.getTo() + " SMTP Info: " + smtpDispatcherProperties.getSmtpHost() + ":" + smtpDispatcherProperties.getSmtpPort(); eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.WRITING, info)); try { Email email = null; if (smtpDispatcherProperties.isHtml()) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charsetEncoding); email.setHostName(smtpDispatcherProperties.getSmtpHost()); try { email.setSmtpPort(Integer.parseInt(smtpDispatcherProperties.getSmtpPort())); } catch (NumberFormatException e) { // Don't set if the value is invalid } try { int timeout = Integer.parseInt(smtpDispatcherProperties.getTimeout()); email.setSocketTimeout(timeout); email.setSocketConnectionTimeout(timeout); } catch (NumberFormatException e) { // Don't set if the value is invalid } // This has to be set before the authenticator because a session shouldn't be created yet configuration.configureEncryption(connectorProperties, email); if (smtpDispatcherProperties.isAuthentication()) { email.setAuthentication(smtpDispatcherProperties.getUsername(), smtpDispatcherProperties.getPassword()); } Properties mailProperties = email.getMailSession().getProperties(); // These have to be set after the authenticator, so that a new mail session isn't created configuration.configureMailProperties(mailProperties); if (smtpDispatcherProperties.isOverrideLocalBinding()) { mailProperties.setProperty("mail.smtp.localaddress", smtpDispatcherProperties.getLocalAddress()); mailProperties.setProperty("mail.smtp.localport", smtpDispatcherProperties.getLocalPort()); } /* * NOTE: There seems to be a bug when calling setTo with a List (throws a * java.lang.ArrayStoreException), so we are using addTo instead. */ for (String to : StringUtils.split(smtpDispatcherProperties.getTo(), ",")) { email.addTo(to); } // Currently unused for (String cc : StringUtils.split(smtpDispatcherProperties.getCc(), ",")) { email.addCc(cc); } // Currently unused for (String bcc : StringUtils.split(smtpDispatcherProperties.getBcc(), ",")) { email.addBcc(bcc); } // Currently unused for (String replyTo : StringUtils.split(smtpDispatcherProperties.getReplyTo(), ",")) { email.addReplyTo(replyTo); } for (Entry<String, String> header : smtpDispatcherProperties.getHeaders().entrySet()) { email.addHeader(header.getKey(), header.getValue()); } email.setFrom(smtpDispatcherProperties.getFrom()); email.setSubject(smtpDispatcherProperties.getSubject()); AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider(); String body = attachmentHandlerProvider.reAttachMessage(smtpDispatcherProperties.getBody(), connectorMessage); if (StringUtils.isNotEmpty(body)) { if (smtpDispatcherProperties.isHtml()) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } } /* * If the MIME type for the attachment is missing, we display a warning and set the * content anyway. If the MIME type is of type "text" or "application/xml", then we add * the content. If it is anything else, we assume it should be Base64 decoded first. */ for (Attachment attachment : smtpDispatcherProperties.getAttachments()) { String name = attachment.getName(); String mimeType = attachment.getMimeType(); String content = attachment.getContent(); byte[] bytes; if (StringUtils.indexOf(mimeType, "/") < 0) { logger.warn("valid MIME type is missing for email attachment: \"" + name + "\", using default of text/plain"); attachment.setMimeType("text/plain"); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding, false); } else if ("application/xml".equalsIgnoreCase(mimeType) || StringUtils.startsWith(mimeType, "text/")) { logger.debug("text or XML MIME type detected for attachment \"" + name + "\""); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding, false); } else { logger.debug("binary MIME type detected for attachment \"" + name + "\", performing Base64 decoding"); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, null, true); } ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null); } /* * From the Commons Email JavaDoc: send returns * "the message id of the underlying MimeMessage". */ responseData = email.send(); responseStatus = Status.SENT; responseStatusMessage = "Email sent successfully."; } catch (Exception e) { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Error sending email message", e)); responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error sending email message", e); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), "Error sending email message", e); // TODO: Exception handling // connector.handleException(new Exception(e)); } finally { eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.IDLE)); } return new Response(responseStatus, responseData, responseStatusMessage, responseError); }
From source file:com.ms.commons.message.impl.sender.AbstractEmailSender.java
private MultiPartEmail makeHtmlEmail(MsunMail mail, String charset) throws EmailException { HtmlEmail email = new HtmlEmail(); email.setCharset(charset);//from w ww. j a v a 2 s. co m if (!StringUtils.isEmpty(mail.getMessage())) { email.setTextMsg(mail.getMessage()); } email.setHtmlMsg(mail.getHtmlMessage()); return email; }