List of usage examples for org.apache.commons.mail Email setSmtpPort
public void setSmtpPort(final int aPortNumber)
From source file:org.openhab.io.net.actions.Mail.java
/** * Sends an email with attachment via SMTP * /*w ww . j a v a2 s. c om*/ * @param to the email address of the recipient * @param subject the subject of the email * @param message the body of the email * @param attachmentUrl a URL string of the content to send as an attachment * * @return <code>true</code>, if sending the email has been successful and * <code>false</code> in all other cases. */ static public boolean sendMail(String to, String subject, String message, String attachmentUrl) { boolean success = false; if (initialized) { Email email = new SimpleEmail(); if (attachmentUrl != null) { // Create the attachment try { email = new MultiPartEmail(); EmailAttachment attachment = new EmailAttachment(); attachment.setURL(new URL(attachmentUrl)); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setName("Attachment"); ((MultiPartEmail) email).attach(attachment); } catch (MalformedURLException e) { logger.error("Invalid attachment url.", e); } catch (EmailException e) { logger.error("Error adding attachment to email.", e); } } email.setHostName(hostname); email.setSmtpPort(port); email.setTLS(tls); if (StringUtils.isNotBlank(username)) { if (popBeforeSmtp) { email.setPopBeforeSmtp(true, hostname, username, password); } else { email.setAuthenticator(new DefaultAuthenticator(username, password)); } } try { email.setFrom(from); email.addTo(to); if (!StringUtils.isEmpty(subject)) email.setSubject(subject); if (!StringUtils.isEmpty(message)) email.setMsg(message); email.send(); logger.debug("Sent email to '{}' with subject '{}'.", to, subject); success = true; } catch (EmailException e) { logger.error("Could not send e-mail to '" + to + ".", e); } } else { logger.error( "Cannot send e-mail because of missing configuration settings. The current settings are: " + "Host: '{}', port '{}', from '{}', useTLS: {}, username: '{}', password '{}'", new String[] { hostname, String.valueOf(port), from, String.valueOf(tls), username, password }); } return success; }
From source file:org.ow2.frascati.akka.fabric.peakforecast.lib.EmailImpl.java
@Override public void send(String message) { try {//from ww w. j av a 2s . c om Email email = new SimpleEmail(); email.setHostName("smtp.googlemail.com"); email.setSmtpPort(465); //email.setAuthenticator(new DefaultAuthenticator("username", "password")); email.setAuthenticator(new DefaultAuthenticator("fouomenedaniel@gmail.com", "motdepasse")); email.setSSLOnConnect(true); email.setFrom("fouomenedaniel@gmail.com"); email.setSubject("Alert PeakForecast"); email.setMsg(message); String listtabmail[] = listEmails.split(" "); for (int i = 0; i < listtabmail.length; i++) { email.addTo(listtabmail[i]); } email.send(); System.out.println("Message Email envoy !!!"); } catch (EmailException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.paxml.bean.EmailTag.java
private Email createEmail(Collection<String> to, Collection<String> cc, Collection<String> bcc) throws EmailException { Email email; if (attachment == null || attachment.isEmpty()) { email = new SimpleEmail(); } else {//from w w w .j a v a 2s . com MultiPartEmail mpemail = new MultiPartEmail(); for (Object att : attachment) { mpemail.attach(makeAttachment(att.toString())); } email = mpemail; } if (StringUtils.isNotEmpty(username)) { String pwd = null; if (password instanceof Secret) { pwd = ((Secret) password).getDecrypted(); } else if (password != null) { pwd = password.toString(); } email.setAuthenticator(new DefaultAuthenticator(username, pwd)); } email.setHostName(findHost()); email.setSSLOnConnect(ssl); if (port > 0) { if (ssl) { email.setSslSmtpPort(port + ""); } else { email.setSmtpPort(port); } } if (replyTo != null) { for (Object r : replyTo) { email.addReplyTo(r.toString()); } } email.setFrom(from); email.setSubject(subject); email.setMsg(text); if (to != null) { for (String r : to) { email.addTo(r); } } if (cc != null) { for (String r : cc) { email.addCc(r); } } if (bcc != null) { for (String r : bcc) { email.addBcc(r); } } email.setSSLCheckServerIdentity(sslCheckServerIdentity); email.setStartTLSEnabled(tls); email.setStartTLSRequired(tls); return email; }
From source file:org.pepstock.jem.notify.engine.EmailNotifier.java
/** * This method sends an <code>Email</code>. <br> * It sets in the parameter <code>Email</code> the properties of the * parameter <code>JemEmail</code>: From User Email Address, From User Name, * subject, text, email destination addresses. <br> * It sets in the parameter <code>Email</code> the Email Server property and * the optional <code>SMTP</code> port, the properties that indicates if it * must use <code>SSL</code> and <code>TLS</code> protocol, the useirid and * password for <code>SMTP</code> server authentication if needed, the * optional bounce address, the subject, the text, and the recipients of the * email./* w ww . j ava2 s.c o m*/ * * @param email the <code>JemEmail</code> with the properties of the email * to be sent. * @param sendingEmail the real <code>Email</code> that will be sent. * @see JemEmail * @see Email * @throws SendMailException if an error occurs. */ private void sendEmail(JemEmail email, Email sendingEmail) throws SendMailException { try { sendingEmail.setHostName(this.emailServer); if (this.smtpPort != NO_SMTP_PORT) { sendingEmail.setSmtpPort(this.smtpPort); } sendingEmail.setFrom(email.getFromUserEmailAddress(), email.getFromUserName()); if (email.hasSubject()) { sendingEmail.setSubject(email.getSubject()); } else { // log no subject LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Subject"); } if (email.hasText()) { sendingEmail.setMsg(email.getText()); } else { // log no text message LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Text Message"); } sendingEmail.setTo(email.getAllToEmailAddresses()); if (null != this.bounceAddress) { sendingEmail.setBounceAddress(this.bounceAddress); } sendingEmail.setSentDate(new Date()); sendingEmail.setSSL(this.isSSL); sendingEmail.setTLS(this.isTLS); if (null != this.authenticationUserId && null != this.authenticationPassword) { sendingEmail.setAuthenticator( new DefaultAuthenticator(this.authenticationUserId, this.authenticationPassword)); } sendingEmail.send(); LogAppl.getInstance().emit(NotifyMessage.JEMN015I, email); } catch (EmailException eEx) { LogAppl.getInstance().emit(NotifyMessage.JEMN016E, eEx, email); throw new SendMailException(NotifyMessage.JEMN016E.toMessage().getFormattedMessage(email), eEx); } }
From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java
public void testCommonsEmailOneWaySeparateSessions() { Queue emailQueue = null;// ww w . j a v a 2 s .c o m MessageConsumer consumer = null; MessageProducer producer = null; Session clientSession = null; Session listenerSession = null; // it is not necessary to use the Email interface here // Email is used here just to allow for multiple types of emails to // occupy // the same varaible. SimpleEmail etc can each be used directly. List<Email> emails = new ArrayList<Email>(); EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null, null, null, null); emails.add(new SimpleEmail(messagingService)); emails.add(new MultiPartEmail(messagingService)); emails.add(new HtmlEmail(messagingService)); try { listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); emailQueue = listenerSession.createQueue(emailQueueName); consumer = listenerSession.createConsumer(emailQueue); consumer.setMessageListener(new EmailListener()); listenerConn.start(); listenerSession.run(); } catch (JMSException e2) { e2.printStackTrace(); Assert.assertTrue(false); } Wiser smtpServer = new Wiser(); smtpServer.setPort(smtpTestPort); smtpServer.start(); try { clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE); emailQueue = clientSession.createQueue(emailQueueName); producer = clientSession.createProducer(emailQueue); clientConn.start(); clientSession.run(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } for (Email em : emails) { try { em.addTo(TEST_EMAIL_TO); em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL); // host and port will be ignored since the email session is // established // by // the listener em.setHostName("localhost"); em.setSmtpPort(smtpTestPort); em.setSubject(TEST_EMAIL_SUBJECT); if (em instanceof HtmlEmail) { em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL); } else if (em instanceof MultiPartEmail) { em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL); } else if (em instanceof SimpleEmail) { em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL); } } catch (EmailException e1) { Assert.assertTrue(false); e1.printStackTrace(); } try { em.buildMimeMessage(); } catch (EmailException e1) { e1.printStackTrace(); Assert.assertTrue(false); } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { em.getMimeMessage().writeTo(os); } catch (javax.mail.MessagingException e) { e.printStackTrace(); Assert.assertTrue(false); } catch (IOException e) { e.printStackTrace(); Assert.assertTrue(false); } String content = os.toString(); ObjectMessage om; try { om = clientSession.createObjectMessage(content); om.setJMSType(emailType); LOG.info("Client: Sending test message...."); producer.send(om); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } } long start = System.currentTimeMillis(); while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) { // wait for transport } Assert.assertTrue(listenerMessagesProcessed == 3); List<WiserMessage> messages = smtpServer.getMessages(); Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3); for (WiserMessage wisermsg : messages) { String body = null; String subject = null; MimeMessage testmail = null; try { testmail = wisermsg.getMimeMessage(); } catch (MessagingException e) { Assert.assertTrue(false); e.printStackTrace(); } if (testmail != null) { LOG.info("SMTP server: test email received: "); try { LOG.info("To: " + testmail.getHeader("To", ",")); LOG.info("Subject: " + testmail.getHeader("Subject", ",")); body = getBodyAsString(testmail.getContent()); subject = testmail.getHeader("Subject", ","); } catch (MessagingException e) { Assert.assertTrue(false); e.printStackTrace(); } catch (IOException e) { Assert.assertTrue(false); e.printStackTrace(); } LOG.info("Body: " + body); Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT)); Assert.assertTrue(body.contains("This is a Commons")); } else { Assert.assertTrue(false); } } if (clientSession != null) { try { clientSession.close(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } clientSession = null; } if (listenerSession != null) { try { listenerSession.close(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } listenerSession = null; } smtpServer.stop(); }
From source file:org.sonatype.nexus.internal.email.EmailManagerImpl.java
/** * Apply server configuration to email.//from w w w . j a va2 s . c om */ @VisibleForTesting Email apply(final EmailConfiguration configuration, final Email mail) throws EmailException { mail.setHostName(configuration.getHost()); mail.setSmtpPort(configuration.getPort()); mail.setAuthentication(configuration.getUsername(), configuration.getPassword()); mail.setStartTLSEnabled(configuration.isStartTlsEnabled()); mail.setStartTLSRequired(configuration.isStartTlsRequired()); mail.setSSLOnConnect(configuration.isSslOnConnectEnabled()); mail.setSSLCheckServerIdentity(configuration.isSslCheckServerIdentityEnabled()); mail.setSslSmtpPort(Integer.toString(configuration.getPort())); // default from address if (mail.getFromAddress() == null) { mail.setFrom(configuration.getFromAddress()); } // apply subject prefix if configured String subjectPrefix = configuration.getSubjectPrefix(); if (subjectPrefix != null) { String subject = mail.getSubject(); mail.setSubject(String.format("%s %s", subjectPrefix, subject)); } // do this last (mail properties are set up from the email fields when you get the mail session) if (configuration.isNexusTrustStoreEnabled()) { SSLContext context = trustStore.getSSLContext(); Session session = mail.getMailSession(); Properties properties = session.getProperties(); properties.remove(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_CLASS); properties.put(EmailConstants.MAIL_SMTP_SSL_ENABLE, true); properties.put("mail.smtp.ssl.socketFactory", context.getSocketFactory()); } return mail; }
From source file:org.structr.common.MailHelper.java
private static void setup(final Email mail, final String to, final String toName, final String from, final String fromName, final String cc, final String bcc, final String bounce, final String subject) throws EmailException { // FIXME: this might be slow if the config file is read each time final Properties config = Services.getInstance().getCurrentConfig(); final String smtpHost = config.getProperty(Services.SMTP_HOST, "localhost"); final String smtpPort = config.getProperty(Services.SMTP_PORT, "25"); final String smtpUser = config.getProperty(Services.SMTP_USER); final String smtpPassword = config.getProperty(Services.SMTP_PASSWORD); final String smtpUseTLS = config.getProperty(Services.SMTP_USE_TLS, "true"); final String smtpRequireTLS = config.getProperty(Services.SMTP_REQUIRE_TLS, "false"); mail.setCharset(charset);/*from ww w . j av a 2 s . c o m*/ mail.setHostName(smtpHost); mail.setSmtpPort(Integer.parseInt(smtpPort)); mail.setStartTLSEnabled(Boolean.parseBoolean(smtpUseTLS)); mail.setStartTLSRequired(Boolean.parseBoolean(smtpRequireTLS)); mail.setCharset(charset); mail.setHostName(smtpHost); mail.setSmtpPort(Integer.parseInt(smtpPort)); if (StringUtils.isNotBlank(smtpUser) && StringUtils.isNotBlank(smtpPassword)) { mail.setAuthentication(smtpUser, smtpPassword); } mail.addTo(to, toName); mail.setFrom(from, fromName); if (StringUtils.isNotBlank(cc)) { mail.addCc(cc); } if (StringUtils.isNotBlank(bcc)) { mail.addBcc(bcc); } if (StringUtils.isNotBlank(bounce)) { mail.setBounceAddress(bounce); } mail.setSubject(subject); }
From source file:org.thousandturtles.gmail_demo.Main.java
public static void main(String[] args) { MailInfoRetriever retriever = new CLIMailInfoRetriever(); MailInfo mailInfo = retriever.retrieveMailInfo(); if (mailInfo.isNoAuth()) { System.out.println("Using No auth, mail with aspmx.l.google.com"); } else {/*from w ww. j a v a 2s . c o m*/ System.out.printf("Username: %s%n", mailInfo.getUsername()); System.out.printf("Password: %c***%c%n", mailInfo.getPassword().charAt(0), mailInfo.getPassword().charAt(mailInfo.getPassword().length() - 1)); } System.out.printf("Mail target: %s%n", mailInfo.getMailTo()); try { Email mail = new SimpleEmail(); if (mailInfo.isNoAuth()) { mail.setHostName("aspmx.l.google.com"); mail.setSmtpPort(25); mail.setFrom("no-reply@thousandturtles.org"); } else { mail.setHostName("smtp.gmail.com"); mail.setSmtpPort(465); mail.setAuthentication(mailInfo.getUsername(), mailInfo.getPassword()); mail.setSSLOnConnect(true); mail.setFrom(mailInfo.getMailer()); } mail.setCharset("UTF-8"); mail.addTo(mailInfo.getMailTo(), "White Mouse"); mail.setSubject(""); mail.setMsg("?\nThis is a test mail!\n"); mail.send(); System.out.println("Mail sent successfully."); } catch (EmailException ee) { ee.printStackTrace(); } }
From source file:org.ygl.plexc.PlexcLibrary.java
/** * Sends an email or text notification upon successful access. * @param requester/*w w w . j a v a 2s . c om*/ * @return */ public boolean notify_1(Term requester) { final String user = getCurrentUser(); final String host = "localhost"; final String subject = "PlexC access notification"; final String text = String.format("%s, %s has been granted access to your location.", user, requester.getTerm().toString()); Email email = new SimpleEmail(); email.setSubject(subject); email.setHostName(host); email.setSmtpPort(465); try { email.setFrom("noreply@plexc.com"); email.setMsg(text); email.addTo(user); email.send(); } catch (EmailException e) { LOG.warn(e.getMessage()); return false; } return true; }
From source file:paquetes.AlertSchedule.java
@Schedule(hour = "8", dayOfWeek = "*", info = "Todos los dias a las 8:00 a.m.") //@Schedule(second = "*", minute = "*/10", hour = "*", persistent= true, info = "cada 10 minutos") public void performTask() throws EmailException { long timeInit = System.currentTimeMillis(); ConfiguracionMail();/* w w w . j a va 2 s .co m*/ log.info(":. Inicio TareaProgramada cada dia"); try { timeInit = System.currentTimeMillis(); obtenerAlertas(); // Luego de obtener las alertas las recorremos para conformar cada uno de los selects de validacion alertas.stream().forEach((ale) -> { id_ale = ale.getId_ale(); llenarAlertasUsuarios(ale.getId_ale()); verificarPorTipoAlerta(ale); nom_tip_ale = ale.getNom_tip_ale(); logale.stream().forEach((lgal) -> { try { Email email = new SimpleEmail(); email.setHostName(this.hostname); email.setSmtpPort(Integer.parseInt(this.smtp_port)); email.setAuthenticator(new DefaultAuthenticator(this.user, this.pass)); // TLS agregado para server AWS Se quita comentario a setSSL. email.setStartTLSEnabled(true); email.setStartTLSRequired(true); // Comentariado para funcionar con Gmail //email.setSSLOnConnect(true); email.setFrom(this.remitente); email.setSubject(nom_tip_ale); email.setMsg(lgal.getAle_des()); alertasusuarios.stream().forEach((mailDestino) -> { try { email.addTo(mailDestino.getMailusu()); } catch (Exception e) { System.out.println("Error en la obtencion de destinatarios. " + e.getMessage()); } }); email.send(); } catch (Exception e) { System.out.println("Error en la conformacion del correo. " + e.getMessage()); } }); }); } catch (Exception e) { log.error("Error en la tarea programada"); log.info(e); } long time = System.currentTimeMillis(); time = System.currentTimeMillis() - timeInit; log.info(":. Fin tarea programada. Tiempo de proceso = " + time); }