List of usage examples for org.apache.commons.mail HtmlEmail setTextMsg
public HtmlEmail setTextMsg(final String aText) throws EmailException
From source file:br.com.hslife.imobiliaria.service.EmailService.java
/** * Envia email no formato HTML// w w w . ja v a2s .c om * * @param nomeRemetente * @param nomeDestinatario * @param emailRemetente * @param emailDestinatario * @param assunto * @param mensagem * @param anexo * * @throws EmailException * @throws MalformedURLException */ public void enviaEmailFormatoHtml(String nomeRementente, String emailRemetente, String nomeDestinatario, String emailDestinatario, String assunto, StringBuilder mensagem, String anexo) throws EmailException, MalformedURLException { HtmlEmail email = new HtmlEmail(); // adiciona uma imagem ao corpo da mensagem e retorna seu id URL url = new URL(anexo); // URL do arquivo a ser anexado String cid = email.embed(url, "Anexos"); // configura a mensagem para o formato HTML email.setHtmlMsg("<html>Anexos</html>"); // configure uma mensagem alternativa caso o servidor no suporte HTML email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML"); email.setHostName("smtp.hslife.com.br"); // o servidor SMTP para envio do e-mail email.addTo(emailDestinatario, nomeDestinatario); //destinatrio email.setFrom(emailRemetente, nomeRementente); // remetente email.setSubject(assunto); // assunto do e-mail email.setMsg(mensagem.toString()); //conteudo do e-mail email.setAuthentication("realimoveis@hslife.com.br", "real123"); //email.setSmtpPort(465); //email.setSSL(true); //email.setTLS(true); // envia email email.send(); }
From source file:br.com.hslife.catu.service.EmailService.java
/** * Envia email no formato HTML//from w w w .j ava 2 s.com * * @param nomeRemetente * @param nomeDestinatario * @param emailRemetente * @param emailDestinatario * @param assunto * @param mensagem * @param anexo * * @throws EmailException * @throws MalformedURLException */ public void enviaEmailFormatoHtml(String nomeRementente, String emailRemetente, String nomeDestinatario, String emailDestinatario, String assunto, StringBuilder mensagem, String anexo) throws EmailException, MalformedURLException { HtmlEmail email = new HtmlEmail(); // adiciona uma imagem ao corpo da mensagem e retorna seu id URL url = new URL(anexo); // URL do arquivo a ser anexado String cid = email.embed(url, "Anexos"); // configura a mensagem para o formato HTML email.setHtmlMsg("<html>Anexos</html>"); // configure uma mensagem alternativa caso o servidor no suporte HTML email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML"); email.setHostName("smtp.hslife.com.br"); // o servidor SMTP para envio do e-mail email.addTo(emailDestinatario, nomeDestinatario); //destinatrio email.setFrom(emailRemetente, nomeRementente); // remetente email.setSubject(assunto); // assunto do e-mail email.setMsg(mensagem.toString()); //conteudo do e-mail email.setAuthentication("realimoveis@hslife.com.br", "real123"); email.setCharset("UTF8"); //email.setSmtpPort(465); //email.setSSL(true); //email.setTLS(true); // envia email email.send(); }
From source file:edu.wright.cs.fa15.ceg3120.concon.server.EmailManager.java
/** * Add an outgoing email to the queue./*from ww w . jav a 2 s . c o m*/ * @param to Array of email addresses. * @param subject Header * @param body Content * @param attachmentFile Attachment */ public void addEmail(String[] to, String subject, String body, File attachmentFile) { HtmlEmail mail = new HtmlEmail(); Properties sysProps = System.getProperties(); // Setup mail server sysProps.setProperty("mail.smtp.host", props.getProperty("mail_server_hostname")); Session session = Session.getDefaultInstance(sysProps); try { mail.setMailSession(session); mail.setFrom(props.getProperty("server_email_addr"), props.getProperty("server_title")); mail.addTo(to); mail.setSubject(subject); mail.setTextMsg(body); mail.setHtmlMsg(composeAsHtml(mail, body)); if (attachmentFile.exists()) { EmailAttachment attachment = new EmailAttachment(); attachment.setPath(attachmentFile.getPath()); mail.attach(attachment); } } catch (EmailException e) { LOG.warn("Email was not added. ", e); } mailQueue.add(mail); }
From source file:com.elexcode.emailservicelibrary.service.EmailSenderServiceImpl.java
@Override public void sendEmail(EmailObject emailObject) throws Exception { HtmlEmail email = new HtmlEmail(); email.setHostName(host);/*from ww w . j av a 2 s. co m*/ email.setSmtpPort(port); email.setAuthentication(username, password); for (String recipient : emailObject.getRecipients()) { email.addTo(recipient); } email.setFrom(username); email.setSubject(emailObject.getSubject()); if (checkStringNotNullNotEmpty(emailObject.getHtmlMsg())) { email.setHtmlMsg(emailObject.getHtmlMsg()); } else { if (checkStringNotNullNotEmpty(emailObject.getMessage())) { email.setTextMsg(emailObject.getMessage()); } } email.setDebug(false); email.setTLS(true); email.setSSL(true); email.send(); }
From source file:br.vn.Model.Filtros.Email.java
public void enviarHatml(String emailcliente) throws MalformedURLException { try {//from w ww. j a v a 2 s. c om // Criar a mensagem de e-mail HtmlEmail email = new HtmlEmail(); email.setHostName("org.apache.commons"); email.addTo("jdoe@somewhere.org", "John Doe"); email.setFrom("me@apache.org", "Me"); email.setSubject("Test email with inline image"); //incorporar a imagem e obter o ID de contedo URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif"); String cid = email.embed(url, "Apache logo"); // definir a mensagem HTML email.setHtmlMsg("<html>The apache logo - <img src=\"cid:" + cid + "\"></html>"); // definir a mensagem alternativa email.setTextMsg("Your email client does not support HTML messages"); // enviar o e-mail email.send(); } catch (EmailException ex) { Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.baasbox.service.user.UserService.java
public static void sendResetPwdMail(String appCode, ODocument user) throws Exception { final String errorString = "Cannot send mail to reset the password: "; //check method input if (!user.getSchemaClass().getName().equalsIgnoreCase(UserDao.MODEL_NAME)) throw new PasswordRecoveryException(errorString + " invalid user object"); //initialization String siteUrl = Application.NETWORK_HTTP_URL.getValueAsString(); int sitePort = Application.NETWORK_HTTP_PORT.getValueAsInteger(); if (StringUtils.isEmpty(siteUrl)) throw new PasswordRecoveryException(errorString + " invalid site url (is empty)"); String textEmail = PasswordRecovery.EMAIL_TEMPLATE_TEXT.getValueAsString(); String htmlEmail = PasswordRecovery.EMAIL_TEMPLATE_HTML.getValueAsString(); if (StringUtils.isEmpty(htmlEmail)) htmlEmail = textEmail;// w w w. j a v a 2 s .c o m if (StringUtils.isEmpty(htmlEmail)) throw new PasswordRecoveryException(errorString + " text to send is not configured"); boolean useSSL = PasswordRecovery.NETWORK_SMTP_SSL.getValueAsBoolean(); boolean useTLS = PasswordRecovery.NETWORK_SMTP_TLS.getValueAsBoolean(); String smtpHost = PasswordRecovery.NETWORK_SMTP_HOST.getValueAsString(); int smtpPort = PasswordRecovery.NETWORK_SMTP_PORT.getValueAsInteger(); if (StringUtils.isEmpty(smtpHost)) throw new PasswordRecoveryException(errorString + " SMTP host is not configured"); String username_smtp = null; String password_smtp = null; if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) { username_smtp = PasswordRecovery.NETWORK_SMTP_USER.getValueAsString(); password_smtp = PasswordRecovery.NETWORK_SMTP_PASSWORD.getValueAsString(); if (StringUtils.isEmpty(username_smtp)) throw new PasswordRecoveryException(errorString + " SMTP username is not configured"); } String emailFrom = PasswordRecovery.EMAIL_FROM.getValueAsString(); String emailSubject = PasswordRecovery.EMAIL_SUBJECT.getValueAsString(); if (StringUtils.isEmpty(emailFrom)) throw new PasswordRecoveryException(errorString + " sender email is not configured"); try { String userEmail = ((ODocument) user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER)).field("email") .toString(); String username = (String) ((ODocument) user.field("user")).field("name"); //Random String sRandom = appCode + "%%%%" + username + "%%%%" + UUID.randomUUID(); String sBase64Random = new String(Base64.encodeBase64(sRandom.getBytes())); //Save on DB ResetPwdDao.getInstance().create(new Date(), sBase64Random, user); //Send mail HtmlEmail email = null; URL resetUrl = new URL(Application.NETWORK_HTTP_SSL.getValueAsBoolean() ? "https" : "http", siteUrl, sitePort, "/user/password/reset/" + sBase64Random); //HTML Email Text ST htmlMailTemplate = new ST(htmlEmail, '$', '$'); htmlMailTemplate.add("link", resetUrl); htmlMailTemplate.add("user_name", username); htmlMailTemplate.add("token", sBase64Random); //Plain text Email Text ST textMailTemplate = new ST(textEmail, '$', '$'); textMailTemplate.add("link", resetUrl); textMailTemplate.add("user_name", username); textMailTemplate.add("token", sBase64Random); email = new HtmlEmail(); email.setHtmlMsg(htmlMailTemplate.render()); email.setTextMsg(textMailTemplate.render()); //Email Configuration email.setSSL(useSSL); email.setSSLOnConnect(useSSL); email.setTLS(useTLS); email.setStartTLSEnabled(useTLS); email.setStartTLSRequired(useTLS); email.setSSLCheckServerIdentity(false); email.setSslSmtpPort(String.valueOf(smtpPort)); email.setHostName(smtpHost); email.setSmtpPort(smtpPort); email.setCharset("utf-8"); if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) { email.setAuthenticator(new DefaultAuthenticator(username_smtp, password_smtp)); } email.setFrom(emailFrom); email.addTo(userEmail); email.setSubject(emailSubject); if (BaasBoxLogger.isDebugEnabled()) { StringBuilder logEmail = new StringBuilder().append("HostName: ").append(email.getHostName()) .append("\n").append("SmtpPort: ").append(email.getSmtpPort()).append("\n") .append("SslSmtpPort: ").append(email.getSslSmtpPort()).append("\n") .append("SSL: ").append(email.isSSL()).append("\n").append("TLS: ").append(email.isTLS()) .append("\n").append("SSLCheckServerIdentity: ").append(email.isSSLCheckServerIdentity()) .append("\n").append("SSLOnConnect: ").append(email.isSSLOnConnect()).append("\n") .append("StartTLSEnabled: ").append(email.isStartTLSEnabled()).append("\n") .append("StartTLSRequired: ").append(email.isStartTLSRequired()).append("\n") .append("SubType: ").append(email.getSubType()).append("\n") .append("SocketConnectionTimeout: ").append(email.getSocketConnectionTimeout()).append("\n") .append("SocketTimeout: ").append(email.getSocketTimeout()).append("\n") .append("FromAddress: ").append(email.getFromAddress()).append("\n").append("ReplyTo: ") .append(email.getReplyToAddresses()).append("\n").append("BCC: ") .append(email.getBccAddresses()).append("\n").append("CC: ").append(email.getCcAddresses()) .append("\n") .append("Subject: ").append(email.getSubject()).append("\n") //the following line throws a NPE in debug mode //.append("Message: ").append(email.getMimeMessage().getContent()).append("\n") .append("SentDate: ").append(email.getSentDate()).append("\n"); BaasBoxLogger.debug("Password Recovery is ready to send: \n" + logEmail.toString()); } email.send(); } catch (EmailException authEx) { BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(authEx)); throw new PasswordRecoveryException( errorString + " Could not reach the mail server. Please contact the server administrator"); } catch (Exception e) { BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(e)); throw new Exception(errorString, e); } }
From source file:de.maklerpoint.office.Schnittstellen.Email.MultiEmailSender.java
public void send() throws EmailException { if (files != null && urls != null) { attachments = new EmailAttachment[files.length + urls.length]; int cnt = 0; for (int i = 0; i < files.length; i++) { attachments[cnt] = new EmailAttachment(); attachments[cnt].setPath(files[i].getPath()); attachments[cnt].setName(files[i].getName()); attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT); cnt++;/*w ww . ja va2 s.c o m*/ } for (int i = 0; i < urls.length; i++) { attachments[cnt] = new EmailAttachment(); attachments[cnt].setURL(urls[i]); attachments[cnt].setName(urls[i].getFile()); attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT); cnt++; } } else if (files != null) { attachments = new EmailAttachment[files.length]; for (int i = 0; i < files.length; i++) { attachments[i] = new EmailAttachment(); attachments[i].setPath(files[i].getPath()); attachments[i].setName(files[i].getName()); attachments[i].setDisposition(EmailAttachment.ATTACHMENT); } } else if (urls != null) { attachments = new EmailAttachment[urls.length]; for (int i = 0; i < urls.length; i++) { attachments[i] = new EmailAttachment(); attachments[i].setURL(urls[i]); attachments[i].setName(urls[i].getFile()); attachments[i].setDisposition(EmailAttachment.ATTACHMENT); } } HtmlEmail email = new HtmlEmail(); email.setHostName(Config.get("mailHost", "")); email.setSmtpPort(Config.getConfigInt("mailPort", 25)); email.setTLS(Config.getConfigBoolean("mailTLS", false)); email.setSSL(Config.getConfigBoolean("mailSSL", false)); //email.setSslSmtpPort(Config.getConfigInt("emailPort", 25)); email.setAuthenticator( new DefaultAuthenticator(Config.get("mailUsername", ""), Config.get("mailPassword", ""))); email.setFrom(Config.get("mailSendermail", "info@example.de"), Config.get("mailSender", null)); email.setSubject(subject); email.setHtmlMsg(body); email.setTextMsg(nohtmlmsg); for (int i = 0; i < adress.length; i++) { email.addTo(adress[i]); } if (cc != null) { for (int i = 0; i < cc.length; i++) { email.addCc(cc[i]); } } if (attachments != null) { for (int i = 0; i < attachments.length; i++) { email.attach(attachments[i]); } } email.send(); }
From source file:Email.CommonsEmail.java
/** * Envia email no formato HTML/*w w w . jav 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:com.itcs.commons.email.impl.RunnableSendHTMLEmail.java
public void run() { Logger.getLogger(RunnableSendHTMLEmail.class.getName()).log(Level.INFO, "executing Asynchronous task RunnableSendHTMLEmail"); try {/*from w w w. j a v a 2s .c o m*/ HtmlEmail email = new HtmlEmail(); email.setCharset("utf-8"); email.setMailSession(getSession()); for (String dir : to) { email.addTo(dir); } if (cc != null) { for (String ccEmail : cc) { email.addCc(ccEmail); } } if (cco != null) { for (String ccoEmail : cco) { email.addBcc(ccoEmail); } } email.setSubject(subject); // set the html message email.setHtmlMsg(body); email.setFrom(getSession().getProperties().getProperty(Email.MAIL_SMTP_FROM, Email.MAIL_SMTP_USER), getSession().getProperties().getProperty(Email.MAIL_SMTP_FROMNAME, Email.MAIL_SMTP_USER)); // set the alternative message email.setTextMsg("Si ve este mensaje, significa que su cliente de correo no permite mensajes HTML."); // send the email if (attachments != null) { addAttachments(email, attachments); } email.send(); Logger.getLogger(RunnableSendHTMLEmail.class.getName()).log(Level.INFO, "Email sent successfully to:{0} cc:{1} bcc:{2}", new Object[] { Arrays.toString(to), Arrays.toString(cc), Arrays.toString(cco) }); } catch (EmailException e) { Logger.getLogger(RunnableSendHTMLEmail.class.getName()).log(Level.SEVERE, "EmailException Error sending email... with properties:\n" + session.getProperties(), e); } }
From source file:de.cosmocode.palava.services.mail.EmailFactory.java
@SuppressWarnings("unchecked") Email build(Document document, Embedder embed) throws EmailException, FileNotFoundException { /* CHECKSTYLE:ON */ final Element root = document.getRootElement(); final List<Element> messages = root.getChildren("message"); if (messages.isEmpty()) throw new IllegalArgumentException("No messages found"); final List<Element> attachments = root.getChildren("attachment"); final Map<ContentType, String> available = new HashMap<ContentType, String>(); for (Element element : messages) { final String type = element.getAttributeValue("type"); final ContentType messageType = StringUtils.equals(type, "html") ? ContentType.HTML : ContentType.PLAIN; if (available.containsKey(messageType)) { throw new IllegalArgumentException("Two messages with the same types have been defined."); }/*from w w w. ja v a2 s . c om*/ available.put(messageType, element.getText()); } final Email email; if (available.containsKey(ContentType.HTML) || attachments.size() > 0) { final HtmlEmail htmlEmail = new HtmlEmail(); htmlEmail.setCharset(CHARSET); if (embed.hasEmbeddings()) { htmlEmail.setSubType("related"); } else if (attachments.size() > 0) { htmlEmail.setSubType("related"); } else { htmlEmail.setSubType("alternative"); } /** * Add html message */ if (available.containsKey(ContentType.HTML)) { htmlEmail.setHtmlMsg(available.get(ContentType.HTML)); } /** * Add plain text alternative */ if (available.containsKey(ContentType.PLAIN)) { htmlEmail.setTextMsg(available.get(ContentType.PLAIN)); } /** * Embedded binary data */ for (Map.Entry<String, String> entry : embed.getEmbeddings().entrySet()) { final String path = entry.getKey(); final String cid = entry.getValue(); final String name = embed.name(path); final File file; if (path.startsWith(File.separator)) { file = new File(path); } else { file = new File(embed.getResourcePath(), path); } if (file.exists()) { htmlEmail.embed(new FileDataSource(file), name, cid); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } /** * Attached binary data */ for (Element attachment : attachments) { final String name = attachment.getAttributeValue("name", ""); final String description = attachment.getAttributeValue("description", ""); final String path = attachment.getAttributeValue("path"); if (path == null) throw new IllegalArgumentException("Attachment path was not set"); File file = new File(path); if (!file.exists()) file = new File(embed.getResourcePath(), path); if (file.exists()) { htmlEmail.attach(new FileDataSource(file), name, description); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } email = htmlEmail; } else if (available.containsKey(ContentType.PLAIN)) { email = new SimpleEmail(); email.setCharset(CHARSET); email.setMsg(available.get(ContentType.PLAIN)); } else { throw new IllegalArgumentException("No valid message found in template."); } final String subject = root.getChildText("subject"); email.setSubject(subject); final Element from = root.getChild("from"); final String fromAddress = from == null ? null : from.getText(); final String fromName = from == null ? fromAddress : from.getAttributeValue("name", fromAddress); email.setFrom(fromAddress, fromName); final Element to = root.getChild("to"); if (to != null) { final String toAddress = to.getText(); if (StringUtils.isNotBlank(toAddress) && toAddress.contains(EMAIL_SEPARATOR)) { final String[] toAddresses = toAddress.split(EMAIL_SEPARATOR); for (String address : toAddresses) { email.addTo(address); } } else if (StringUtils.isNotBlank(toAddress)) { final String toName = to.getAttributeValue("name", toAddress); email.addTo(toAddress, toName); } } final Element cc = root.getChild("cc"); if (cc != null) { final String ccAddress = cc.getText(); if (StringUtils.isNotBlank(ccAddress) && ccAddress.contains(EMAIL_SEPARATOR)) { final String[] ccAddresses = ccAddress.split(EMAIL_SEPARATOR); for (String address : ccAddresses) { email.addCc(address); } } else if (StringUtils.isNotBlank(ccAddress)) { final String ccName = cc.getAttributeValue("name", ccAddress); email.addCc(ccAddress, ccName); } } final Element bcc = root.getChild("bcc"); if (bcc != null) { final String bccAddress = bcc.getText(); if (StringUtils.isNotBlank(bccAddress) && bccAddress.contains(EMAIL_SEPARATOR)) { final String[] bccAddresses = bccAddress.split(EMAIL_SEPARATOR); for (String address : bccAddresses) { email.addBcc(address); } } else if (StringUtils.isNotBlank(bccAddress)) { final String bccName = bcc.getAttributeValue("name", bccAddress); email.addBcc(bccAddress, bccName); } } final Element replyTo = root.getChild("replyTo"); if (replyTo != null) { final String replyToAddress = replyTo.getText(); if (StringUtils.isNotBlank(replyToAddress) && replyToAddress.contains(EMAIL_SEPARATOR)) { final String[] replyToAddresses = replyToAddress.split(EMAIL_SEPARATOR); for (String address : replyToAddresses) { email.addReplyTo(address); } } else if (StringUtils.isNotBlank(replyToAddress)) { final String replyToName = replyTo.getAttributeValue("name", replyToAddress); email.addReplyTo(replyToAddress, replyToName); } } return email; }