List of usage examples for org.apache.commons.mail Email send
public String send() throws EmailException
From source file:com.pkrete.locationservice.admin.mailer.impl.BasicEmailService.java
/** * Send an email to the given user when the user is created or the password * is modified./*from www.ja v a2 s. co m*/ * * @param user the receiver of the email */ @Override public void send(UserFull user) { logger.info("Create new email message."); Email email = new SimpleEmail(); email.setHostName(PropertiesUtil.getProperty("mail.host")); email.setSmtpPort(this.converterService.strToInt(PropertiesUtil.getProperty("mail.port"))); email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getProperty("mail.user"), PropertiesUtil.getProperty("mail.password"))); email.setTLS(true); try { // Init variables String header = null; String msg = null; // Set from address email.setFrom(this.messageSource.getMessage("mail.from", null, null)); // Set message arguments Object[] args = new Object[] { user.getUsername(), user.getPasswordUi() }; // Set variables values if (user.getUpdated() == null) { // This is a new user if (logger.isDebugEnabled()) { logger.debug("The message is for a new user."); } // Set subject email.setSubject(this.messageSource.getMessage("mail.title.add", null, null)); // Set message header header = this.messageSource.getMessage("mail.header.add", null, null); // Set message content msg = this.messageSource.getMessage("mail.message.add", args, null); } else { // This is an existing user logger.debug("The message is for an existing user."); // Set subject email.setSubject(this.messageSource.getMessage("mail.title.edit", null, null)); // Get message header header = this.messageSource.getMessage("mail.header.edit", null, null); // Get message content msg = this.messageSource.getMessage("mail.message.edit", args, null); } // Get note String note = this.messageSource.getMessage("mail.note", null, null); // Get footer String footer = this.messageSource.getMessage("mail.footer", null, null); // Get signature String signature = this.messageSource.getMessage("mail.signature", null, null); // Build message body StringBuilder result = new StringBuilder(); if (!header.isEmpty()) { result.append(header).append("\n\n"); } if (!msg.isEmpty()) { result.append(msg).append("\n\n"); } if (!note.isEmpty()) { result.append(note).append("\n\n"); } if (!footer.isEmpty()) { result.append(footer).append("\n\n"); } if (!signature.isEmpty()) { result.append(signature).append("\n\n"); } // Set message contents email.setMsg(result.toString()); // Set message receiver email.addTo(user.getEmail()); // Send message email.send(); logger.info("Email was sent to \"{}\".", user.getEmail()); } catch (Exception e) { logger.error("Failed to send email to \"{}\".", user.getEmail()); logger.error(e.getMessage(), e); } }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
@Override public ConnectionTestResponse sendTestEmail(Properties properties) throws Exception { String portString = properties.getProperty("port"); String encryption = properties.getProperty("encryption"); String host = properties.getProperty("host"); String timeoutString = properties.getProperty("timeout"); Boolean authentication = Boolean.parseBoolean(properties.getProperty("authentication")); String username = properties.getProperty("username"); String password = properties.getProperty("password"); String to = properties.getProperty("toAddress"); String from = properties.getProperty("fromAddress"); int port = -1; try {// w ww . j a va 2 s .c om port = Integer.parseInt(portString); } catch (NumberFormatException e) { return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Invalid port: \"" + portString + "\""); } Email email = new SimpleEmail(); email.setDebug(true); email.setHostName(host); email.setSmtpPort(port); try { int timeout = Integer.parseInt(timeoutString); email.setSocketTimeout(timeout); email.setSocketConnectionTimeout(timeout); } catch (NumberFormatException e) { // Don't set if the value is invalid } if ("SSL".equalsIgnoreCase(encryption)) { email.setSSLOnConnect(true); email.setSslSmtpPort(portString); } else if ("TLS".equalsIgnoreCase(encryption)) { email.setStartTLSEnabled(true); } if (authentication) { email.setAuthentication(username, password); } // These have to be set after the authenticator, so that a new mail session isn't created ConfigurationController configurationController = ControllerFactory.getFactory() .createConfigurationController(); String protocols = properties.getProperty("protocols", StringUtils.join( MirthSSLUtil.getEnabledHttpsProtocols(configurationController.getHttpsClientProtocols()), ' ')); String cipherSuites = properties.getProperty("cipherSuites", StringUtils.join( MirthSSLUtil.getEnabledHttpsCipherSuites(configurationController.getHttpsCipherSuites()), ' ')); email.getMailSession().getProperties().setProperty("mail.smtp.ssl.protocols", protocols); email.getMailSession().getProperties().setProperty("mail.smtp.ssl.ciphersuites", cipherSuites); SSLSocketFactory socketFactory = (SSLSocketFactory) properties.get("socketFactory"); if (socketFactory != null) { email.getMailSession().getProperties().put("mail.smtp.ssl.socketFactory", socketFactory); if ("SSL".equalsIgnoreCase(encryption)) { email.getMailSession().getProperties().put("mail.smtp.socketFactory", socketFactory); } } email.setSubject("Mirth Connect Test Email"); try { for (String toAddress : StringUtils.split(to, ",")) { email.addTo(toAddress); } email.setFrom(from); email.setMsg( "Receipt of this email confirms that mail originating from this Mirth Connect Server is capable of reaching its intended destination.\n\nSMTP Configuration:\n- Host: " + host + "\n- Port: " + port); email.send(); return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS, "Sucessfully sent test email to: " + to); } catch (EmailException e) { return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, e.getMessage()); } }
From source file:easycar.controller.BookingListController.java
public void emailRemind() { Email email = new SimpleEmail(); email.setHostName("smtp.googlemail.com"); email.setSmtpPort(465);/* ww w . ja va 2 s . c o m*/ email.setAuthenticator(new DefaultAuthenticator("easycarremind", "easycartest")); email.setSSLOnConnect(true); try { email.setFrom("easycarremind@gmail.com"); email.setSubject("Reminder to return car"); email.setMsg("Dear " + selectedBooking.getCustomerName() + ",\n\nPlease note that you are supposed to return the car with id " + selectedBooking.getCarId() + " to us on " + selectedBooking.getEndDateToDisplay() + "\n\nBest regards,\nEasy Car Team."); email.addTo(selectedBooking.getCustomerEmail()); email.send(); } catch (EmailException e) { e.printStackTrace(); } selectedBooking.setLastEmailRemindDate(getZeroTimeDate(new Date())); try { bookingService.editBooking(selectedBooking); } catch (IOException e) { e.printStackTrace(); } FacesContext.getCurrentInstance().addMessage("messageDetailDialog", new FacesMessage( FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("REMINDER_SENT"), null)); }
From source file:easycar.controller.BookingListController.java
public void emailRemindAll() { FullBookingDto currentFullBookingDto; for (int i = 0; i < baseFullBookingList.size(); i++) { currentFullBookingDto = baseFullBookingList.get(i); if (!currentFullBookingDto.isRemindButtonOn()) { continue; }/*from w w w . ja v a 2s.co m*/ Email email = new SimpleEmail(); email.setHostName("smtp.googlemail.com"); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator("easycarremind", "easycartest")); email.setSSLOnConnect(true); try { email.setFrom("easycarremind@gmail.com"); email.setSubject("Reminder to return car"); email.setMsg("Dear " + currentFullBookingDto.getCustomerName() + ",\n\nPlease note that you are supposed to return the car with id " + currentFullBookingDto.getCarId() + " to us on " + currentFullBookingDto.getEndDateToDisplay() + "\n\nBest regards,\nEasy Car Team."); email.addTo(currentFullBookingDto.getCustomerEmail()); email.send(); } catch (EmailException e) { e.printStackTrace(); } currentFullBookingDto.setLastEmailRemindDate(getZeroTimeDate(new Date())); try { bookingService.editBooking(currentFullBookingDto); } catch (IOException e) { e.printStackTrace(); } } FacesContext.getCurrentInstance().addMessage("messageEmailRemindAll", new FacesMessage( FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("REMINDER_SENT"), null)); }
From source file:com.mirth.connect.connectors.smtp.SmtpMessageDispatcher.java
@Override public void doDispatch(UMOEvent event) throws Exception { monitoringController.updateStatus(connector, connectorType, Event.BUSY); MessageObject mo = messageObjectController.getMessageObjectFromEvent(event); if (mo == null) { return;/*ww w . j a v a 2 s . c om*/ } try { Email email = null; if (connector.isHtml()) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(connector.getCharsetEncoding()); email.setHostName(replacer.replaceValues(connector.getSmtpHost(), mo)); try { email.setSmtpPort(Integer.parseInt(replacer.replaceValues(connector.getSmtpPort(), mo))); } catch (NumberFormatException e) { // Don't set if the value is invalid } try { email.setSocketConnectionTimeout( Integer.parseInt(replacer.replaceValues(connector.getTimeout(), mo))); } catch (NumberFormatException e) { // Don't set if the value is invalid } if ("SSL".equalsIgnoreCase(connector.getEncryption())) { email.setSSL(true); } else if ("TLS".equalsIgnoreCase(connector.getEncryption())) { email.setTLS(true); } if (connector.isAuthentication()) { email.setAuthentication(replacer.replaceValues(connector.getUsername(), mo), replacer.replaceValues(connector.getPassword(), mo)); } /* * 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 : replaceValuesAndSplit(connector.getTo(), mo)) { email.addTo(to); } // Currently unused for (String cc : replaceValuesAndSplit(connector.cc(), mo)) { email.addCc(cc); } // Currently unused for (String bcc : replaceValuesAndSplit(connector.getBcc(), mo)) { email.addBcc(bcc); } // Currently unused for (String replyTo : replaceValuesAndSplit(connector.getReplyTo(), mo)) { email.addReplyTo(replyTo); } for (Entry<String, String> header : connector.getHeaders().entrySet()) { email.addHeader(replacer.replaceValues(header.getKey(), mo), replacer.replaceValues(header.getValue(), mo)); } email.setFrom(replacer.replaceValues(connector.getFrom(), mo)); email.setSubject(replacer.replaceValues(connector.getSubject(), mo)); String body = replacer.replaceValues(connector.getBody(), mo); if (connector.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 : connector.getAttachments()) { String name = replacer.replaceValues(attachment.getName(), mo); String mimeType = replacer.replaceValues(attachment.getMimeType(), mo); String content = replacer.replaceValues(attachment.getContent(), mo); 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 = content.getBytes(); } else if ("application/xml".equalsIgnoreCase(mimeType) || StringUtils.startsWith(mimeType, "text/")) { logger.debug("text or XML MIME type detected for attachment \"" + name + "\""); bytes = content.getBytes(); } else { logger.debug("binary MIME type detected for attachment \"" + name + "\", performing Base64 decoding"); bytes = Base64.decodeBase64(content); } ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null); } /* * From the Commons Email JavaDoc: send returns * "the message id of the underlying MimeMessage". */ String response = email.send(); messageObjectController.setSuccess(mo, response, null); } catch (EmailException e) { alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_402, "Error sending email message.", e); messageObjectController.setError(mo, Constants.ERROR_402, "Error sending email message.", e, null); connector.handleException(new Exception(e)); } finally { monitoringController.updateStatus(connector, connectorType, Event.DONE); } }
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;/* www . ja v a 2 s. co 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:net.wikiadmin.clientnotification.SendMain.java
/** sendMainText. */ void sendMainText(String cMail, String cName, String cCredit) { /* i need your data!!! :D */ XmlProp readData = new XmlProp("mailsettings.xml"); readData.readData();/*from ww w. j a v a2s . c om*/ userS = readData.getUser(); passS = readData.getpass(); hostS = readData.gethost(); portS = readData.getport(); sslS = readData.getssl(); fromS = readData.getfrom(); toS = cMail; intPortS = Integer.parseInt(portS); sslBoolean = Boolean.parseBoolean(sslS); themeText = readData.getTheme(); bodyText = readData.getBody() + cName + ".\n" + readData.getBodyP2() + cCredit + readData.getBodyP3() + "\n" + readData.getBodyContacts(); try { Email email = new SimpleEmail(); email.setHostName(hostS); email.setAuthenticator(new DefaultAuthenticator(userS, passS)); email.setSSLOnConnect(sslBoolean); email.setSmtpPort(intPortS); email.setFrom(fromS); email.setSubject(themeText); email.setMsg(bodyText); email.addTo(toS); email.send(); } catch (EmailException ex) { ex.printStackTrace(); System.out.println(""); } }
From source file:org.activiti.engine.impl.bpmn.behavior.MailActivityBehavior.java
public void execute(ActivityExecution execution) { boolean doIgnoreException = Boolean.parseBoolean(getStringFromField(ignoreException, execution)); String exceptionVariable = getStringFromField(exceptionVariableName, execution); Email email = null; try {//from ww w. ja v a 2s. c o m String toStr = getStringFromField(to, execution); String fromStr = getStringFromField(from, execution); String ccStr = getStringFromField(cc, execution); String bccStr = getStringFromField(bcc, execution); String subjectStr = getStringFromField(subject, execution); String textStr = textVar == null ? getStringFromField(text, execution) : getStringFromField(getExpression(execution, textVar), execution); String htmlStr = htmlVar == null ? getStringFromField(html, execution) : getStringFromField(getExpression(execution, htmlVar), execution); String charSetStr = getStringFromField(charset, execution); email = createEmail(textStr, htmlStr); addTo(email, toStr); setFrom(email, fromStr); addCc(email, ccStr); addBcc(email, bccStr); setSubject(email, subjectStr); setMailServerProperties(email); setCharset(email, charSetStr); email.send(); } catch (ActivitiException e) { handleException(execution, e.getMessage(), e, doIgnoreException, exceptionVariable); } catch (EmailException e) { handleException(execution, "Could not send e-mail in execution " + execution.getId(), e, doIgnoreException, exceptionVariable); } leave(execution); }
From source file:org.activiti5.engine.impl.bpmn.behavior.MailActivityBehavior.java
@Override public void execute(DelegateExecution execution) { boolean doIgnoreException = Boolean.parseBoolean(getStringFromField(ignoreException, execution)); String exceptionVariable = getStringFromField(exceptionVariableName, execution); Email email = null; try {/* www . ja v a 2 s . co m*/ String toStr = getStringFromField(to, execution); String fromStr = getStringFromField(from, execution); String ccStr = getStringFromField(cc, execution); String bccStr = getStringFromField(bcc, execution); String subjectStr = getStringFromField(subject, execution); String textStr = textVar == null ? getStringFromField(text, execution) : getStringFromField(getExpression(execution, textVar), execution); String htmlStr = htmlVar == null ? getStringFromField(html, execution) : getStringFromField(getExpression(execution, htmlVar), execution); String charSetStr = getStringFromField(charset, execution); List<File> files = new LinkedList<File>(); List<DataSource> dataSources = new LinkedList<DataSource>(); getFilesFromFields(attachments, execution, files, dataSources); email = createEmail(textStr, htmlStr, attachmentsExist(files, dataSources)); addTo(email, toStr); setFrom(email, fromStr, execution.getTenantId()); addCc(email, ccStr); addBcc(email, bccStr); setSubject(email, subjectStr); setMailServerProperties(email, execution.getTenantId()); setCharset(email, charSetStr); attach(email, files, dataSources); email.send(); } catch (ActivitiException e) { handleException(execution, e.getMessage(), e, doIgnoreException, exceptionVariable); } catch (EmailException e) { handleException(execution, "Could not send e-mail in execution " + execution.getId(), e, doIgnoreException, exceptionVariable); } leave((ActivityExecution) execution); }
From source file:org.apache.airavata.credential.store.notifier.impl.EmailNotifier.java
public void notifyMessage(NotificationMessage message) throws CredentialStoreException { try {/*from w w w . ja v a2 s . c om*/ Email email = new SimpleEmail(); email.setHostName(this.emailNotifierConfiguration.getEmailServer()); email.setSmtpPort(this.emailNotifierConfiguration.getEmailServerPort()); email.setAuthenticator(new DefaultAuthenticator(this.emailNotifierConfiguration.getEmailUserName(), this.emailNotifierConfiguration.getEmailPassword())); email.setSSLOnConnect(this.emailNotifierConfiguration.isSslConnect()); email.setFrom(this.emailNotifierConfiguration.getFromAddress()); EmailNotificationMessage emailMessage = (EmailNotificationMessage) message; email.setSubject(emailMessage.getSubject()); email.setMsg(emailMessage.getMessage()); email.addTo(emailMessage.getSenderEmail()); email.send(); } catch (EmailException e) { log.error("[CredentialStore]Error sending email notification message."); throw new CredentialStoreException("Error sending email notification message", e); } }