List of usage examples for org.apache.commons.mail MultiPartEmail MultiPartEmail
MultiPartEmail
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;/*w w w .j a v a 2s .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:de.knurt.fam.template.controller.letter.EMailLetterAdapter.java
private Email getEMail(File file, EMailLetterAdapter mailIn) { // attachment EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getAbsolutePath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("Attachment"); // INTLANG attachment.setName(file.getName()); // INTLANG // email message MultiPartEmail email = new MultiPartEmail(); try {/*ww w.j av a 2 s. c o m*/ // basics email.addTo(mailIn.getTo()); email.setFrom(mailIn.getFrom()); email.setSubject(mailIn.getSubject()); email.setMsg(mailIn.getMsg()); // add attachment email.attach(attachment); } catch (EmailException e) { FamLog.exception(e, 201106131739l); email = null; } return email; }
From source file:info.toegepaste.controller.PdfController.java
public void CreatePdf(long studentId) { //Fonts/*from w w w.j ava 2s . c o m*/ Font header = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD); Font normal = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL); //Declaration Student student = new Student(); List<Course> courses; List<Exam> exams = null; Score score; int totaal = 0; //totaal van een vak berekenen int maxScore = 0; //max soore van een test int aantalVakken = 0; //aantal vakken waaraan student heeft deelgenomen int klasgemiddelde = 0; //hulpvariabele om klasgemiddelde op te vragen Double totaalGemiddelde = 0.0; //eindpercentage Double vermenigvuldigfactor = 0.0; //om score op 20 weer te geven ArrayList<Integer> gemiddeldes = new ArrayList<Integer>(); //gemiddeldes per vak ArrayList<Integer> gemiddeldesKlas = new ArrayList<Integer>(); //gemiddelde klas per vak PdfPCell cell; //Document Document document = new Document(); //student opvullen student = pdfService.getStudent(studentId); //Tempfix //student.getClassgroup(); //cursussen opvullen courses = courseService.getWithClassgroup(student.getClassgroup()); for (int i = 0; i < courses.size(); i++) { //testen opvullen exams = pdfService.getExamsByCourse(courses.get(i)); for (int j = 0; j < exams.size(); j++) { score = pdfService.getScoreByExamAndStudent(exams.get(j), student); //nagaan of de student heeft deelgenomen aan de test if (score != null) { // score op 20 weergeven vermenigvuldigfactor = 20 / (double) exams.get(j).getTotal(); totaal += (int) (score.getScore() * vermenigvuldigfactor); } //klasgemiddelde voor een vak klasgemiddelde = pdfService.getAverageScoreByExam(exams.get(j)); gemiddeldesKlas.add(klasgemiddelde); } if (exams.size() > 0) { gemiddeldes.add(totaal / exams.size()); totaalGemiddelde += totaal / exams.size(); aantalVakken++; } totaal = 0; exams.clear(); } totaalGemiddelde = totaalGemiddelde / aantalVakken * 5; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { PdfWriter.getInstance(document, outputStream); document.open(); //header document.add(new Paragraph("Studenten Rapport", header)); document.add(new Paragraph("Student:" + student.getFirstname() + " " + student.getLastname(), normal)); document.add(new Paragraph("Klas:" + student.getClassgroup(), normal)); document.add(new Paragraph("Alle scores worden op 20 weergegeven", normal)); //table PdfPTable table = new PdfPTable(3); //create tableheaders PdfPCell c1 = new PdfPCell(new Phrase("Vak")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Score")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); c1 = new PdfPCell(new Phrase("Gemiddelde")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); table.setHeaderRows(1); for (int i = 0; i < aantalVakken; i++) { cell = new PdfPCell(new Phrase(gemiddeldes.get(i).toString())); if (gemiddeldes.get(i) < 10) { cell.setBackgroundColor(BaseColor.RED); } table.addCell(courses.get(i).getName()); table.addCell(cell); table.addCell(gemiddeldesKlas.get(i).toString()); } document.add(table); //end document.add(new Paragraph("Totaal behaald percentage:" + totaalGemiddelde, normal)); document.close(); } catch (DocumentException e) { e.printStackTrace(); // } catch (FileNotFoundException e) { // e.printStackTrace(); } MultiPartEmail email = new MultiPartEmail(); email.setHostName("smtp.googlemail.com"); email.setSmtpPort(587); email.setSSLOnConnect(true); email.setAuthenticator(new DefaultAuthenticator("bitmescoretracker@gmail.com", "bitmeScore")); try { email.addTo(student.getEmail()); email.setFrom("bitmescoretracker@gmail.com"); email.setSubject("Requested scores , scoretracker"); email.setMsg("Here are the scores you requested!"); // EmailAttachment attachment = new EmailAttachment(); //attachment.setDescription("PDF met uw punten"); // attachment.setName(student.getFirstname() + " " + student.getLastname() + " scores"); byte[] bytes = outputStream.toByteArray(); DataSource source = new javax.mail.util.ByteArrayDataSource(bytes, "application/pdf"); System.out.println("Stuff"); /* try{ source = outputStream.write(bytes); }catch(IOException e){ e.printStackTrace(); }*/ email.attach(source, student.getFirstname() + " " + student.getLastname() + " scores", "stuff"); email.send(); } catch (EmailException ex) { ex.printStackTrace(); } }
From source file:core.messaging.Messenger.java
private void sendImmediately(final String to, final String from, final String subject, final String body, ByteArrayDataSource attachment) { try {/* w w w .j a v a 2 s.c o m*/ logger.log(Level.INFO, "Sending email to={0},from={1},subject={2},body={3},attachment={4},fileName{5},mimeType={6}", new Object[] { to, from, subject, body, attachment, attachment == null ? "null" : attachment.getName(), attachment == null ? "null" : attachment.getContentType() }); // Create the email message MultiPartEmail email = new MultiPartEmail(); email.addTo(to); email.setFrom(from); email.setSubject(subject); email.setMsg(body); String logLocation = Play.configuration.getProperty("log.mail"); logger.log(Level.FINE, "logging message to {0}, attachment size={1}", new Object[] { logLocation, attachment == null ? 0 : attachment.getBytes().length }); long timestamp = System.currentTimeMillis(); //TODO * log email contents also (body) FileLogHelper.createInstance().log(logLocation, to + "-" + timestamp, email.getSubject().getBytes()); if (attachment != null) { String attachmentName = to + "-" + timestamp + "-attachment-" + attachment.getName(); FileLogHelper.createInstance().log(logLocation, attachmentName, attachment.getBytes()); // add the attachment EmailAttachment emailAttachment = new EmailAttachment(); //write to mailerbean dir then read from there, that is fine emailAttachment.setPath(logLocation + "/" + attachmentName); emailAttachment.setDisposition(EmailAttachment.ATTACHMENT); emailAttachment.setDescription(attachment.getName()); emailAttachment.setName(attachment.getName()); email.attach(emailAttachment); } logger.log(Level.FINE, "Sending message"); Future<Boolean> send = Mail.send(email); } catch (Exception ex) { Logger.getLogger(Messenger.class.getName()).log(Level.SEVERE, null, ex); throw new MessangerException(ex); } }
From source file:com.irurueta.server.commons.email.ApacheMailSender.java
/** * Method to send a multipart email./*from w ww. j a v a 2 s. c o m*/ * @param m email message to be sent. * @return id of message that has been sent. * @throws MailNotSentException if mail couldn't be sent. */ public String sendMultiPartEmail(EmailMessage<MultiPartEmail> m) throws MailNotSentException { try { MultiPartEmail email = new MultiPartEmail(); internalSendApacheEmail(m, email); } catch (Throwable t) { throw new MailNotSentException(t); } return null; }
From source file:com.aurel.track.util.emailHandling.MailSender.java
/** * /*from w w w . jav a 2s . c om*/ * @param smtpMailSettings * @param internetAddressFrom * @param internetAddressesTo * @param subject * @param messageBody * @param isPlain * @param attachments * @param internetAddressesCC * @param internetAddressesBCC * @param internetAddressesReplayTo */ private void init(SMTPMailSettings smtpMailSettings, InternetAddress internetAddressFrom, InternetAddress[] internetAddressesTo, String subject, String messageBody, boolean isPlain, List<LabelValueBean> attachments, InternetAddress[] internetAddressesCC, InternetAddress[] internetAddressesBCC, InternetAddress[] internetAddressesReplayTo) { this.smtpMailSettings = smtpMailSettings; try { if (isPlain) { email = new SimpleEmail(); if (attachments != null && attachments.size() > 0) { email = new MultiPartEmail(); } } else { email = new HtmlEmail(); } if (LOGGER.isTraceEnabled()) { email.setDebug(true); } email.setHostName(smtpMailSettings.getHost()); email.setSmtpPort(smtpMailSettings.getPort()); email.setCharset(smtpMailSettings.getMailEncoding() != null ? smtpMailSettings.getMailEncoding() : DEFAULTENCODINGT); if (timeout != null) { email.setSocketConnectionTimeout(timeout); email.setSocketTimeout(timeout); } if (smtpMailSettings.isReqAuth()) { email = setAuthMode(email); } email = setSecurityMode(email); for (int i = 0; i < internetAddressesTo.length; ++i) { email.addTo(internetAddressesTo[i].getAddress(), internetAddressesTo[i].getPersonal()); } if (internetAddressesCC != null) { for (int i = 0; i < internetAddressesCC.length; ++i) { email.addCc(internetAddressesCC[i].getAddress(), internetAddressesCC[i].getPersonal()); } } if (internetAddressesBCC != null) { for (int i = 0; i < internetAddressesBCC.length; ++i) { email.addBcc(internetAddressesBCC[i].getAddress(), internetAddressesBCC[i].getPersonal()); } } if (internetAddressesReplayTo != null) { for (int i = 0; i < internetAddressesReplayTo.length; ++i) { email.addReplyTo(internetAddressesReplayTo[i].getAddress(), internetAddressesReplayTo[i].getPersonal()); } } email.setFrom(internetAddressFrom.getAddress(), internetAddressFrom.getPersonal()); email.setSubject(subject); String cid = null; if (isPlain) { email.setMsg(messageBody); } else { if (messageBody.contains("cid:$$CID$$")) { URL imageURL = null; InputStream in = null; in = MailSender.class.getClassLoader().getResourceAsStream("tracklogo.gif"); if (in != null) { imageURL = new URL(ApplicationBean.getInstance().getServletContext().getResource("/") + "logoAction.action?type=m"); DataSource ds = new ByteArrayDataSource(in, "image/" + "gif"); cid = ((HtmlEmail) email).embed(ds, "Genji"); } else { String theResource = "/WEB-INF/classes/resources/MailTemplates/tracklogo.gif"; imageURL = ApplicationBean.getInstance().getServletContext().getResource(theResource); cid = ((HtmlEmail) email).embed(imageURL, "Genji"); } messageBody = messageBody.replaceFirst("\\$\\$CID\\$\\$", cid); } Set<String> attachSet = new HashSet<String>(); messageBody = MailImageBL.replaceInlineImages(messageBody, attachSet); if (!attachSet.isEmpty()) { Iterator<String> it = attachSet.iterator(); while (it.hasNext()) { String key = it.next(); StringTokenizer st = new StringTokenizer(key, "_"); String workItemIDStr = st.nextToken(); String attachmentKeyStr = st.nextToken(); TAttachmentBean attachmentBean = null; try { attachmentBean = AttachBL.loadAttachment(Integer.valueOf(attachmentKeyStr), Integer.valueOf(workItemIDStr), true); } catch (Exception ex) { } if (attachmentBean != null) { String fileName = attachmentBean.getFullFileNameOnDisk(); File file = new File(fileName); InputStream is = new FileInputStream(file); DataSource ds = new ByteArrayDataSource(is, "image/" + "gif"); cid = ((HtmlEmail) email).embed(ds, key); messageBody = messageBody.replaceAll("cid:" + key, "cid:" + cid); } } } ((HtmlEmail) email).setHtmlMsg(messageBody); } if (attachments != null && !attachments.isEmpty()) { includeAttachments(attachments); } } catch (Exception e) { LOGGER.error("Something went wrong trying to assemble an e-mail: " + e.getMessage()); } }
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 va 2 s.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:Email.CommonsEmail.java
/** * envia email com arquivo anexo//from ww w . j a v a2 s.c om * * @throws EmailException */ public void enviaEmailComAnexo() throws EmailException { // cria o anexo 1. EmailAttachment anexo1 = new EmailAttachment(); //caminho do arquivo (RAIZ_PROJETO/teste/teste.txt) anexo1.setPath("teste/teste.txt"); anexo1.setDisposition(EmailAttachment.ATTACHMENT); anexo1.setDescription("Exemplo de arquivo anexo"); anexo1.setName("teste.txt"); // cria o anexo 2. EmailAttachment anexo2 = new EmailAttachment(); //caminho do arquivo (RAIZ_PROJETO/teste/teste2.jsp) anexo2.setPath("teste/teste2.jsp"); anexo2.setDisposition(EmailAttachment.ATTACHMENT); anexo2.setDescription("Exemplo de arquivo anexo"); anexo2.setName("teste2.jsp"); // configura o email MultiPartEmail email = new MultiPartEmail(); email.setHostName("smtp.gmail.com"); // o servidor SMTP para envio do e-mail email.addTo("teste@gmail.com", "Guilherme"); //destinatrio email.setFrom("facom.sisges@gmail.com", "SisGES"); // remetente email.setSubject("Teste -> Email com anexos"); // assunto do e-mail email.setMsg("Teste de Email utilizando commons-email"); //conteudo do e-mail email.setAuthentication("teste", "xxxxx"); email.setSmtpPort(465); //email.setSSL(true); //email.setTLS(true); // adiciona arquivo(s) anexo(s) email.attach(anexo1); email.attach(anexo2); // envia o email email.send(); }
From source file:com.ms.commons.message.impl.sender.AbstractEmailSender.java
private MultiPartEmail makeSimpleEmailWithAttachment(MsunMail mail, String charset) throws EmailException { MultiPartEmail email = new MultiPartEmail(); email.setCharset(charset);/*from w w w .j av a 2 s.co m*/ email.setMsg(mail.getMessage()); return email; }
From source file:com.maxl.java.amikodesk.Emailer.java
public void send() { try {//from w w w. j a v a2 s .c om MultiPartEmail email = new MultiPartEmail(); email.setHostName(m_es); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator(m_el, m_ep)); email.setSSLOnConnect(true); // Create email message email.setSubject(m_subject); // Subject email.setMsg(m_body); // Body email.setFrom(m_from); // From field email.addTo(m_recipient); // Recipient if (m_singlecc != null && !m_singlecc.isEmpty()) email.addCc(m_singlecc); // CC if (m_replyTo != null && !m_replyTo.isEmpty()) email.addReplyTo(m_replyTo); // Reply-To // Add attachments for (Map.Entry<String, String> entry : m_map_of_attachments.entrySet()) { EmailAttachment attachment = new EmailAttachment(); attachment.setName(entry.getKey()); attachment.setPath(entry.getValue()); attachment.setDisposition(EmailAttachment.ATTACHMENT); email.attach(attachment); } // Send email email.send(); // Clear map m_map_of_attachments.clear(); } catch (EmailException e) { e.printStackTrace(); } }