List of usage examples for javax.mail.internet MimeMessage addRecipient
public void addRecipient(RecipientType type, Address address) throws MessagingException
From source file:org.cern.flume.sink.mail.MailSink.java
@Override public Status process() throws EventDeliveryException { Status status = null;/*from w w w . ja v a 2 s . c o m*/ // Start transaction Channel ch = getChannel(); Transaction txn = ch.getTransaction(); txn.begin(); try { Event event = ch.take(); if (event != null) { // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", port); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage mimeMessage = new MimeMessage(session); // Set From: header field of the header. mimeMessage.setFrom(new InternetAddress(sender)); // Set To: header field of the header. for (String recipient : recipients) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } // Now set the subject and actual message Map<String, String> headers = event.getHeaders(); String value; String mailSubject = subject; for (String field : subjectFields) { try { if (field.equals("body")) { value = new String(event.getBody()); } else { value = new String(headers.get(field)); } } catch (NullPointerException t) { value = ""; } mailSubject = mailSubject.replace("%{" + field + "}", value); } String mailMessage = message; for (String field : messageFields) { try { if (field.equals("body")) { value = new String(event.getBody()); } else { value = new String(headers.get(field)); } } catch (NullPointerException t) { value = ""; } mailMessage = mailMessage.replace("%{" + field + "}", value); } mimeMessage.setSubject(mailSubject); mimeMessage.setText(mailMessage); // Send message Transport.send(mimeMessage); } txn.commit(); status = Status.READY; } catch (Throwable t) { txn.rollback(); logger.error("Unable to send e-mail.", t); status = Status.BACKOFF; if (t instanceof Error) { throw (Error) t; } } finally { txn.close(); } return status; }
From source file:mx.uatx.tesis.managebeans.IndexMB.java
public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception { try {/*from www.ja v a 2s .c o m*/ // Propiedades de la conexin Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.starttls.enable", "true"); props.setProperty("mail.smtp.port", "587"); props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com"); props.setProperty("mail.smtp.auth", "true"); // Preparamos la sesion Session session = Session.getDefaultInstance(props); // Construimos el mensaje MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("alfons018pbg@gmail.com")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + "")); message.setSubject("Asistencia tcnica"); message.setText("\n \n \n Estimado: " + nombre + " " + apellido + "\n El Servicio Tecnico de SEA ta da la bienvenida. " + "\n Los siguientes son tus datos para acceder:" + "\n Correo: " + corre + "\n Password: " + password2 + ""); // Lo enviamos. Transport t = session.getTransport("smtp"); t.connect("alfons018pbg@gmail.com", "al12fo05zo1990"); t.sendMessage(message, message.getAllRecipients()); // Cierre. t.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.pentaho.reporting.engine.classic.extensions.modules.mailer.MailProcessor.java
private static void processRecipients(final MailDefinition definition, final MimeMessage message, final DataFactory dataFactory, final DataRow parameterDataRow) throws ReportDataFactoryException, MessagingException { if (definition.getRecipientsQuery() != null && dataFactory.isQueryExecutable(definition.getRecipientsQuery(), parameterDataRow)) { final TableModel model = wrapWithParameters( dataFactory.queryData(definition.getRecipientsQuery(), parameterDataRow), parameterDataRow); for (int r = 0; r < model.getRowCount(); r++) { String address = null; String name = null;//from w w w.ja v a 2 s. c o m String type = "TO"; if (model.getColumnCount() >= 3) { type = (String) model.getValueAt(0, 2); } if (model.getColumnCount() >= 2) { name = (String) model.getValueAt(0, 1); } if (model.getColumnCount() >= 1) { address = (String) model.getValueAt(0, 0); } if (address == null) { continue; } if (name == null) { message.addRecipient(parseType(type), new InternetAddress(address, true)); } else { try { message.addRecipient(parseType(type), new InternetAddress(address, name, "UTF-8")); } catch (UnsupportedEncodingException e) { // Should not happen - UTF-8 is safe to use throw new MessagingException("Failed to encode recipient", e); } } } } }
From source file:com.netflix.genie.server.jobmanager.impl.JobMonitor.java
/** * Check the properties file to figure out if an email * needs to be sent at the end of the job. If yes, get * mail properties and try and send email about Job Status. * @return 0 for success, -1 for failure *//*from w ww. j a v a 2s . c om*/ private boolean sendEmail(String emailTo) { logger.debug("called"); if (!config.getBoolean("netflix.genie.server.mail.enable", false)) { logger.warn("Email is disabled but user has specified an email address."); return false; } // Sender's email ID String fromEmail = config.getString("netflix.genie.server.mail.smpt.from", "no-reply-genie@geniehost.com"); logger.info("From email address to use to send email: " + fromEmail); // Set the smtp server hostname. Use localhost as default String smtpHost = config.getString("netflix.genie.server.mail.smtp.host", "localhost"); logger.debug("Email smtp server: " + smtpHost); // Get system properties Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); // check whether authentication should be turned on Authenticator auth = null; if (config.getBoolean("netflix.genie.server.mail.smtp.auth", false)) { logger.debug("Email Authentication Enabled"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); String userName = config.getString("netflix.genie.server.mail.smtp.user"); String password = config.getString("netflix.genie.server.mail.smtp.password"); if ((userName == null) || (password == null)) { logger.error("Authentication is enabled and username/password for smtp server is null"); return false; } logger.debug( "Constructing authenticator object with username" + userName + " and password " + password); auth = new SMTPAuthenticator(userName, password); } else { logger.debug("Email authentication not enabled."); } // Get the default Session object. Session session = Session.getInstance(properties, auth); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(fromEmail)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo)); // Set Subject: header field message.setSubject("Genie Job " + ji.getJobName() + " completed with Status: " + ji.getStatus()); // Now set the actual message String body = "Your Genie Job is complete\n\n" + "Job ID: " + ji.getJobID() + "\n" + "Job Name: " + ji.getJobName() + "\n" + "Status: " + ji.getStatus() + "\n" + "Status Message: " + ji.getStatusMsg() + "\n" + "Output Base URL: " + ji.getOutputURI() + "\n"; message.setText(body); // Send message Transport.send(message); logger.info("Sent email message successfully...."); return true; } catch (MessagingException mex) { logger.error("Got exception while sending email", mex); return false; } }
From source file:com.gtwm.jasperexecute.RunJasperReports.java
public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException { Properties props = new Properties(); //props.setProperty("mail.debug", "true"); props.setProperty("mail.smtp.host", emailHost); if (emailUser != null) { props.setProperty("mail.smtp.auth", "true"); }//ww w . j ava2 s . c o m Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass); Session mailSession = Session.getDefaultInstance(props, emailAuthenticator); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); // transport.connect(emailHost, emailUser, emailPass); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessUnauthorizedEmailSimpleText() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.FALSE); MessageListener mockListener2 = mock(MessageListener.class); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(mockListener2); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Simple text Email test"); mail.setText(textEmailContent);/*from w ww. j a va 2 s . c o m*/ Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(0, event.getMessages().size()); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); }
From source file:com.netflix.genie.server.jobmanager.impl.JobMonitorImpl.java
/** * Check the properties file to figure out if an email needs to be sent at * the end of the job. If yes, get mail properties and try and send email * about Job Status./*ww w. j a v a 2 s .c o m*/ * * @return 0 for success, -1 for failure * @throws GenieException on issue */ private boolean sendEmail(final String emailTo, final boolean killed) throws GenieException { LOG.debug("called"); final Job job = this.jobService.getJob(this.jobId); if (!this.config.getBoolean("com.netflix.genie.server.mail.enable", false)) { LOG.warn("Email is disabled but user has specified an email address."); return false; } // Sender's email ID final String fromEmail = this.config.getString("com.netflix.genie.server.mail.smpt.from", "no-reply-genie@geniehost.com"); LOG.info("From email address to use to send email: " + fromEmail); // Set the smtp server hostname. Use localhost as default final String smtpHost = this.config.getString("com.netflix.genie.server.mail.smtp.host", "localhost"); LOG.debug("Email smtp server: " + smtpHost); // Get system properties final Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); // check whether authentication should be turned on Authenticator auth = null; if (this.config.getBoolean("com.netflix.genie.server.mail.smtp.auth", false)) { LOG.debug("Email Authentication Enabled"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); final String userName = config.getString("com.netflix.genie.server.mail.smtp.user"); final String password = config.getString("com.netflix.genie.server.mail.smtp.password"); if (userName == null || password == null) { LOG.error("Authentication is enabled and username/password for smtp server is null"); return false; } LOG.debug("Constructing authenticator object with username" + userName + " and password " + password); auth = new SMTPAuthenticator(userName, password); } else { LOG.debug("Email authentication not enabled."); } // Get the default Session object. final Session session = Session.getInstance(properties, auth); try { // Create a default MimeMessage object. final MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(fromEmail)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo)); JobStatus jobStatus; if (killed) { jobStatus = JobStatus.KILLED; } else { jobStatus = job.getStatus(); } // Set Subject: header field message.setSubject("Genie Job " + job.getName() + " completed with Status: " + jobStatus); // Now set the actual message final String body = "Your Genie Job is complete\n\n" + "Job ID: " + job.getId() + "\n" + "Job Name: " + job.getName() + "\n" + "Status: " + job.getStatus() + "\n" + "Status Message: " + job.getStatusMsg() + "\n" + "Output Base URL: " + job.getOutputURI() + "\n"; message.setText(body); // Send message Transport.send(message); LOG.info("Sent email message successfully...."); return true; } catch (final MessagingException mex) { LOG.error("Got exception while sending email", mex); return false; } }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailSimpleText() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Simple text Email test"); mail.setText(textEmailContent);// w w w .ja v a 2s .c o m Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Simple text Email test", message.getTitle()); assertEquals(textEmailContent, message.getBody()); assertEquals(textEmailContent.substring(0, 200), message.getSummary()); assertEquals(0, message.getAttachmentsSize()); assertEquals(0, message.getAttachments().size()); assertEquals("componentId", message.getComponentId()); assertEquals("text/plain; charset=" + System.getProperty("file.encoding"), message.getContentType()); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); }
From source file:com.ilopez.jasperemail.JasperEmail.java
public void emailReport(String emailHost, final String emailUser, final String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames, Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException { Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport); Properties props = new Properties(); // Setup Email Settings props.setProperty("mail.smtp.host", emailHost); props.setProperty("mail.smtp.port", smtpport.toString()); props.setProperty("mail.smtp.auth", smtpauth.toString()); if (smtpenc == OptionValues.SMTPType.SSL) { // SSL settings props.put("mail.smtp.socketFactory.port", smtpport.toString()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } else if (smtpenc == OptionValues.SMTPType.TLS) { // TLS Settings props.put("mail.smtp.starttls.enable", "true"); } else {// w ww . j a v a2 s .c o m // Plain } // Setup and Apply the Email Authentication Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailUser, emailPass); } }); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailHtmlText() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Simple html Email test"); String html = loadHtml();/* w w w. j ava 2 s .co m*/ mail.setText(html, "UTF-8", "html"); mail.setSentDate(new Date()); Date sentDate = new Date(mail.getSentDate().getTime()); Transport.send(mail); Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Simple html Email test", message.getTitle()); assertEquals(html, message.getBody()); assertNotNull(message.getSentDate()); assertEquals(sentDate.getTime(), message.getSentDate().getTime()); assertEquals(htmlEmailSummary, message.getSummary()); assertEquals(0, message.getAttachmentsSize()); assertEquals(0, message.getAttachments().size()); assertEquals("componentId", message.getComponentId()); assertEquals("text/html; charset=UTF-8", message.getContentType()); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); }