List of usage examples for org.apache.commons.mail HtmlEmail setHtmlMsg
public HtmlEmail setHtmlMsg(final String aHtml) throws EmailException
From source file:controllers.ProjectApp.java
private static void sendTransferRequestMail(ProjectTransfer pt) { HtmlEmail email = new HtmlEmail(); try {// w w w . j a v a 2s.c o m String acceptUrl = pt.getAcceptUrl(); String message = Messages.get("transfer.message.hello", pt.destination) + "\n\n" + Messages.get("transfer.message.detail", pt.project.name, pt.newProjectName, pt.project.owner, pt.destination) + "\n" + Messages.get("transfer.message.link") + "\n\n" + acceptUrl + "\n\n" + Messages.get("transfer.message.deadline") + "\n\n" + Messages.get("transfer.message.thank"); email.setFrom(Config.getEmailFromSmtp(), pt.sender.name); email.addTo(Config.getEmailFromSmtp(), "Yobi"); User to = User.findByLoginId(pt.destination); if (!to.isAnonymous()) { email.addBcc(to.email, to.name); } Organization org = Organization.findByName(pt.destination); if (org != null) { List<OrganizationUser> admins = OrganizationUser.findAdminsOf(org); for (OrganizationUser admin : admins) { email.addBcc(admin.user.email, admin.user.name); } } email.setSubject( String.format("[%s] @%s wants to transfer project", pt.project.name, pt.sender.loginId)); email.setHtmlMsg(Markdown.render(message)); email.setTextMsg(message); email.setCharset("utf-8"); email.addHeader("References", "<" + acceptUrl + "@" + Config.getHostname() + ">"); email.setSentDate(pt.requested); Mailer.send(email); String escapedTitle = email.getSubject().replace("\"", "\\\""); String logEntry = String.format("\"%s\" %s", escapedTitle, email.getBccAddresses()); play.Logger.of("mail").info(logEntry); } catch (Exception e) { Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e)); } }
From source file:com.ipc.service.SignUpService.java
public String sendhtmlmail(int uid, String key, String email) throws IOException, EmailException { HtmlEmail sendemail = new HtmlEmail(); sendemail.setCharset("euc-kr"); sendemail.setHostName("smtp.worksmobile.com"); sendemail.addTo(email);/*from w w w . ja v a2 s .co m*/ sendemail.setFrom("jinuk@ideaconcert.com", ""); sendemail.setSubject("? ?? ?."); sendemail.setAuthentication("jinuk@ideaconcert.com", "tpxmapsb1"); sendemail.setSmtpPort(465); sendemail.setSSL(true); //? sendemail.setTLS(true); sendemail.setDebug(true); String htmlmsg = "<html><div style='width:1000px; float:left; border-bottom:2px solid #45d4fe; padding-bottom:5px;box-sizing:border-box;'></div><div style='width:1000px;float:left; box-sizing:border-box; padding:15px;'><h2>? ? ? .</h2><div style='width:100%; float:left; box-sizing:border-box; border:5px solid #f9f9f9; text-align:center; padding:40px 0 40px 0;'><span> ? .</span><br><a href='http://localhost:8088/signup/permit?uid=" + uid + "&key=" + key + "'><button style='width:150px; height:40px; background:none; border:2px solid #45d4fe; font-size:1.1rem; text-decoration: none;font-weight:bold; margin-top:10px;'></button></a></div></div></html>"; System.out.println(htmlmsg); sendemail.setHtmlMsg(htmlmsg); try { sendemail.send(); } catch (Exception e) { System.out.println("NOTOK"); return "NOTOK"; } return "OK"; }
From source file:Email.CommonsEmail.java
/** * Envia email no formato HTML/*from w w w . ja v a 2 s.c o 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.duroty.application.chat.manager.ChatManager.java
/** * DOCUMENT ME!//w w w. ja va 2 s .co m * * @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
public void sendingHtml(String destinatario, String nome, String assunto, URL linkBoleto) { try {//from w ww .ja va2 s .c o m // 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, new BusinessDelegate().getMensagem(new BigDecimal(61)).getAssunto()); // localizando a mensagem //Mensagem msg = new Mensagem(); //msg = new BusinessDelegate().getMensagem(mensagemId); // set the html message //email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>"); String body = ""; body += this.htmlHead; body += (this.bodyProfissional); body += ("Faça 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(null); //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) { Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:br.com.itfox.beans.SendHtmlFormatedEmail.java
/** * * @param destinatario//from w w w . j av 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:fr.gouv.culture.thesaurus.util.MailUtil.java
/** * /*from ww w .ja v a 2s . co m*/ * Envoi l'email. * * @throws EmailException * Erreur lors de l'envoi de l'email. */ public void send() throws EmailException { if (hostProperty == null) { log.error("Session email non initialise : envoi des emails impossible."); return; } HtmlEmail email = new HtmlEmail(); email.setHostName(hostProperty); // To if (to != null) { for (String adresse : to) { email.addTo(adresse); } } // Cc if (cc != null) { for (String adresse : cc) { email.addCc(adresse); } } // Cci if (cci != null) { for (String adresse : cci) { email.addBcc(adresse); } } // Subject email.setSubject(subjectPrefix != null ? subjectPrefix + subject : subject); // From email.setFrom(StringUtils.isNotEmpty(from) ? from : defaultFrom); // Message & Html if (message != null) { email.setTextMsg(message); } if (html != null) { email.setHtmlMsg(html); } if (StringUtils.isNotEmpty(this.charset)) { email.setCharset(this.charset); } email.buildMimeMessage(); // Attachments for (AttachmentBean attachement : attachments) { email.attach(attachement.getDataSource(), attachement.getName(), attachement.getDescription()); } email.sendMimeMessage(); }
From source file:de.hybris.platform.acceleratorservices.email.impl.DefaultEmailService.java
@Override public boolean send(final EmailMessageModel message) { if (message == null) { throw new IllegalArgumentException("message must not be null"); }/*from w w w.j a v a 2 s.c om*/ final boolean sendEnabled = getConfigurationService().getConfiguration() .getBoolean(EMAILSERVICE_SEND_ENABLED_CONFIG_KEY, true); if (sendEnabled) { try { final HtmlEmail email = getPerConfiguredEmail(); email.setCharset("UTF-8"); final List<EmailAddressModel> toAddresses = message.getToAddresses(); if (CollectionUtils.isNotEmpty(toAddresses)) { email.setTo(getAddresses(toAddresses)); } else { throw new IllegalArgumentException("message has no To addresses"); } final List<EmailAddressModel> ccAddresses = message.getCcAddresses(); if (ccAddresses != null && !ccAddresses.isEmpty()) { email.setCc(getAddresses(ccAddresses)); } final List<EmailAddressModel> bccAddresses = message.getBccAddresses(); if (bccAddresses != null && !bccAddresses.isEmpty()) { email.setBcc(getAddresses(bccAddresses)); } final EmailAddressModel fromAddress = message.getFromAddress(); email.setFrom(fromAddress.getEmailAddress(), nullifyEmpty(fromAddress.getDisplayName())); // Add the reply to if specified final String replyToAddress = message.getReplyToAddress(); if (replyToAddress != null && !replyToAddress.isEmpty()) { email.setReplyTo(Collections.singletonList(createInternetAddress(replyToAddress, null))); } email.setSubject(message.getSubject()); email.setHtmlMsg(getBody(message)); // To support plain text parts use email.setTextMsg() final List<EmailAttachmentModel> attachments = message.getAttachments(); if (attachments != null && !attachments.isEmpty()) { for (final EmailAttachmentModel attachment : attachments) { try { final DataSource dataSource = new ByteArrayDataSource( getMediaService().getDataFromMedia(attachment), attachment.getMime()); email.attach(dataSource, attachment.getRealFileName(), attachment.getAltText()); } catch (final EmailException ex) { LOG.error("Failed to load attachment data into data source [" + attachment + "]", ex); return false; } } } // Important to log all emails sent out LOG.info("Sending Email [" + message.getPk() + "] To [" + convertToStrings(toAddresses) + "] From [" + fromAddress.getEmailAddress() + "] Subject [" + email.getSubject() + "]"); // Send the email and capture the message ID final String messageID = email.send(); message.setSent(true); message.setSentMessageID(messageID); message.setSentDate(new Date()); getModelService().save(message); return true; } catch (final EmailException e) { LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "] cause: " + e.getMessage()); if (LOG.isDebugEnabled()) { LOG.debug(e); } } } else { LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "]"); LOG.info("Email sending has been disabled. Check the config property 'emailservice.send.enabled'"); return true; } return false; }
From source file:com.jnd.sonar.analysisreport.AnalysisReportHelper.java
private void sendEmail(String reportname, Map<String, String> reportDataMap2) { try {/*from w w w . j a va 2 s .co m*/ // Create the email message //MultiPartEmail email = new MultiPartEmail(); StringBuilder strHtmlContentSummary = new StringBuilder(); System.out.println("Analysis - Sonar Email Notification"); from = settings.getString("sonar.jd.smptp.username"); System.out.println("from=>" + from); to_email = settings.getString("sonar.jd.smptp.to"); System.out.println("to_email=>" + to_email); to_email_name = settings.getString("sonar.jd.smptp.to_name"); System.out.println("to_email_name=>" + to_email_name); username = settings.getString("sonar.jd.smptp.username"); System.out.println("username=>" + username); password = settings.getString("sonar.jd.smptp.password"); System.out.println("password=>" + password); hostname = settings.getString("sonar.jd.smptp.host"); System.out.println("hostname=>" + hostname); portno = settings.getString("sonar.jd.smptp.sslport"); System.out.println("portno=>" + portno); setSSLOnConnectFlag = settings.getBoolean("sonar.jd.smptp.set_ssl_on_connect"); System.out.println("setSSLOnConnectFlag=>" + String.valueOf(setSSLOnConnectFlag)); subject = settings.getString("sonar.jd.smptp.subject"); System.out.println("subject=>" + subject); message = settings.getString("sonar.jd.smptp.message"); System.out.println("message=>" + message); // Create the email message HtmlEmail email = new HtmlEmail(); email.setHostName(hostname); email.setSslSmtpPort(portno); if (!StringUtils.isBlank(username) || !StringUtils.isBlank(password)) { email.setAuthentication(username, password); } //email.setSSLOnConnect(setSSLOnConnectFlag); email.setSSL(setSSLOnConnectFlag); String[] addrs = StringUtils.split(to_email, "\t\r\n;, "); for (String addr : addrs) { email.addTo(addr); } //email.addTo(to_email,to_email_name); email.setFrom(from); email.setSubject(subject); //email.setMsg(message); // embed the image and get the content id URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif"); String cid = email.embed(url, "Apache logo - 1"); System.out.println("Print Entries from Analysis Data Map."); int i = 1; strHtmlContentSummary.append("<html><body>The apache logo - <img src=\"cid:" + cid + "\"><br><br><br><b><center>Metric Information:-</center></b><br><table border='2'>"); for (Map.Entry<String, String> entry : reportDataMap.entrySet()) { strHtmlContentSummary .append("<tr><td>" + entry.getKey() + ":</td><td>" + entry.getValue() + "</td></tr>"); i++; } strHtmlContentSummary.append("</table></body></html>"); System.out.println(strHtmlContentSummary.toString()); // set the html message email.setHtmlMsg(strHtmlContentSummary.toString()); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // Create the attachment EmailAttachment attachment = new EmailAttachment(); attachment.setPath(reportname); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("Sonar Analysis Report" + reportname); attachment.setName(reportname); email.attach(attachment); // send the email System.out.println("Sending the Email"); email.send(); } catch (EmailException e) { throw new SonarException("Unable to send email", e); } catch (Exception ex) { // TODO Auto-generated catch block ex.printStackTrace(); } }
From source file:com.esofthead.mycollab.module.mail.DefaultMailer.java
private HtmlEmail getBasicEmail(String fromEmail, String fromName, List<MailRecipientField> toEmail, List<MailRecipientField> ccEmail, List<MailRecipientField> bccEmail, String subject, String html) { try {/* ww w . j a va 2 s.c o m*/ HtmlEmail email = new HtmlEmail(); email.setHostName(host); email.setFrom(fromEmail, fromName); email.setCharset(EmailConstants.UTF_8); for (int i = 0; i < toEmail.size(); i++) { if (isValidate(toEmail.get(i).getEmail()) && isValidate(toEmail.get(i).getName())) { email.addTo(toEmail.get(i).getEmail(), toEmail.get(i).getName()); } else { LOG.error("Invalid to email input: " + toEmail.get(i).getEmail() + "---" + toEmail.get(i).getName()); } } if (CollectionUtils.isNotEmpty(ccEmail)) { for (int i = 0; i < ccEmail.size(); i++) { if (isValidate(ccEmail.get(i).getEmail()) && isValidate(ccEmail.get(i).getName())) { email.addCc(ccEmail.get(i).getEmail(), ccEmail.get(i).getName()); } else { LOG.error("Invalid cc email input: " + ccEmail.get(i).getEmail() + "---" + ccEmail.get(i).getName()); } } } if (CollectionUtils.isNotEmpty(bccEmail)) { for (int i = 0; i < bccEmail.size(); i++) { if (isValidate(bccEmail.get(i).getEmail()) && isValidate(bccEmail.get(i).getName())) { email.addBcc(bccEmail.get(i).getEmail(), bccEmail.get(i).getName()); } else { LOG.error("Invalid bcc email input: " + bccEmail.get(i).getEmail() + "---" + bccEmail.get(i).getName()); } } } if (username != null) { email.setAuthentication(username, password); } email.setStartTLSEnabled(isTLS); email.setSubject(subject); if (StringUtils.isNotBlank(html)) { email.setHtmlMsg(html); } return email; } catch (EmailException e) { throw new MyCollabException(e); } }