List of usage examples for javax.mail Transport sendMessage
public abstract void sendMessage(Message msg, Address[] addresses) throws MessagingException;
From source file:com.basicservice.service.MailService.java
public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception { try {//from w w w . j av a 2 s. com Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", 587); props.put("mail.smtp.auth", "true"); Authenticator auth = new SMTPAuthenticator(); Session mailSession = Session.getDefaultInstance(props, auth); // mailSession.setDebug(true); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); Multipart multipart = new MimeMultipart("alternative"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html"); multipart.addBodyPart(htmlPart); message.setContent(multipart); message.setFrom(new InternetAddress(from)); message.setSubject(subject, "UTF-8"); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); transport.connect(); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); } catch (Exception e) { LOG.debug("Exception while sending email: ", e); throw e; } }
From source file:com.thoughtworks.go.config.GoSmtpMailSender.java
public ValidationBean send(String subject, String body, String to) { Transport transport = null; try {/* w w w .j a va 2 s. c o m*/ if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Sending email [%s] to [%s]", subject, to)); } Properties props = mailProperties(); MailSession session = MailSession.getInstance().createWith(props, username, password); transport = session.getTransport(); transport.connect(host, port, nullIfEmpty(username), nullIfEmpty(password)); MimeMessage msg = session.createMessage(from, to, subject, body); transport.sendMessage(msg, msg.getRecipients(TO)); return ValidationBean.valid(); } catch (AuthenticationFailedException e) { LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e); return ValidationBean.notValid("Failed to send the email. Caused by: Authentication failed"); } catch (NoSuchProviderException e) { LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e); return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage()); } catch (MessagingException e) { LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e); return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage()); } catch (Exception e) { LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e); return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage()); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException e) { LOGGER.error("Failed to close transport", e); } } } }
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
@Override public void send(final GmailMessage message) { if (message instanceof JavaMailGmailMessage) { Transport transport = null; try {//from w w w . ja v a2s . c o m final JavaMailGmailMessage msg = (JavaMailGmailMessage) message; transport = getGmailTransport(); transport.sendMessage(msg.getMessage(), msg.getMessage().getAllRecipients()); } catch (final Exception e) { throw new GmailException("Failed sending message: " + message, e); } finally { if (transport.isConnected()) { try { transport.close(); } catch (final Exception e) { LOG.warn("Cannot Close ImapGmailConnection : " + transport, e); } } } } else { throw new GmailException("ImapGmailClient requires JavaMailGmailMessage!"); } }
From source file:fsi_admin.JSmtpConn.java
private boolean sendMsg(String HOST, String USERNAME, String PASSWORD, StringBuffer msj, Session session, MimeMessage mmsg, MimeMultipart multipart) { try {/*from www.ja v a 2 s .co m*/ mmsg.setContent(multipart); // Create a transport. Transport transport = session.getTransport(); // Send the message. System.out.println(HOST + " " + USERNAME + " " + PASSWORD); transport.connect(HOST, USERNAME, PASSWORD); // Send the email. transport.sendMessage(mmsg, mmsg.getAllRecipients()); transport.close(); return true; } catch (MessagingException e) { e.printStackTrace(); msj.append("Error de Mensajeria al enviar SMTP: " + e.getMessage()); return false; } catch (Exception ex) { ex.printStackTrace(); msj.append("Error general de mensaje al enviar SMTP: " + ex.getMessage()); return false; } }
From source file:org.exoplatform.chat.server.ChatServer.java
public void sendMailWithAuth(String senderFullname, List<String> toList, String htmlBody, String subject) throws Exception { String host = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_HOST); String user = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_USER); String password = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PASSWORD); String port = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PORT); Properties props = System.getProperties(); props.put("mail.smtp.user", user); props.put("mail.smtp.password", password); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); //props.put("mail.debug", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.EnableSSL.enable", "true"); Session session = Session.getInstance(props, null); //session.setDebug(true); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(user, senderFullname)); // To get the array of addresses for (String to : toList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); }/* www . ja va 2 s . c o m*/ message.setSubject(subject); message.setContent(htmlBody, "text/html"); Transport transport = session.getTransport("smtp"); try { transport.connect(host, user, password); transport.sendMessage(message, message.getAllRecipients()); } finally { transport.close(); } }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { Map parametersMap;//from w ww .ja v a 2 s . c om String contentType; String fileExtension; IDataStore emailDispatchDataStore; String nameSuffix; String descriptionSuffix; String containedFileName; String zipFileName; boolean reportNameInSubject; logger.debug("IN"); try { parametersMap = dispatchContext.getParametersMap(); contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore(); nameSuffix = dispatchContext.getNameSuffix(); descriptionSuffix = dispatchContext.getDescriptionSuffix(); containedFileName = dispatchContext.getContainedFileName() != null && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName() : document.getName(); zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("") ? dispatchContext.getZipMailName() : document.getName(); reportNameInSubject = dispatchContext.isReportNameInSubject(); String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); int smptPort = 25; if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); String mailSubj = dispatchContext.getMailSubj(); mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = dispatchContext.getMailTxt(); String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore); if (recipients == null || recipients.length == 0) { logger.error("No recipients found for email sending!!!"); return false; } //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } //session = Session.getDefaultInstance(props, auth); session = Session.getInstance(props, auth); //session.setDebug(true); //session.setDebugOut(null); logger.info("Session.getInstance(props, auth)"); } else { //session = Session.getDefaultInstance(props); session = Session.getInstance(props); logger.info("Session.getInstance(props)"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type String subject = mailSubj; if (reportNameInSubject) { subject += " " + document.getName() + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt + "\n" + descriptionSuffix); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = null; //if zip requested if (dispatchContext.isZipMailDocument()) { mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension); } //else else { sds = new SchedulerDataSource(executionOutput, contentType, containedFileName + nameSuffix + fileExtension); mbp2.setDataHandler(new DataHandler(sds)); mbp2.setFileName(sds.getName()); } // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smptPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { //Use normal SMTP Transport.send(msg); } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:com.vaushell.superpipes.dispatch.ErrorMailer.java
private void sendHTML(final String message) throws MessagingException, IOException { if (message == null || message.isEmpty()) { throw new IllegalArgumentException("message"); }//from w ww. j a v a 2s . com final String host = properties.getConfigString("host"); final Properties props = System.getProperties(); props.setProperty("mail.smtp.host", host); final String port = properties.getConfigString("port", null); if (port != null) { props.setProperty("mail.smtp.port", port); } if ("true".equalsIgnoreCase(properties.getConfigString("ssl", null))) { props.setProperty("mail.smtp.ssl.enable", "true"); } final Session session = Session.getInstance(props, null); // session.setDebug( true ); final javax.mail.Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(properties.getConfigString("from"))); msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(properties.getConfigString("to"), false)); msg.setSubject("superpipes error message"); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, "text/html"))); msg.setHeader("X-Mailer", "superpipes"); Transport t = null; try { t = session.getTransport("smtp"); final String username = properties.getConfigString("username", null); final String password = properties.getConfigString("password", null); if (username == null || password == null) { t.connect(); } else { if (port == null || port.isEmpty()) { t.connect(host, username, password); } else { t.connect(host, Integer.parseInt(port), username, password); } } t.sendMessage(msg, msg.getAllRecipients()); } finally { if (t != null) { t.close(); } } }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void send() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .sendLine("221 bye").build().start(PORT); Session session = JMSession.getSession(); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); transport.sendMessage(msg, msg.getAllRecipients()); transport.close();/* w ww . java2s .c om*/ server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void quitNoResponse() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .build().start(PORT);//from ww w.j a va2 s. c o m Session session = JMSession.getSession(); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void multilineGreeting() throws Exception { server = MockTcpServer.scenario().sendLine("220-first line").sendLine("220 second line").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .sendLine("221 bye").build().start(PORT); Session session = JMSession.getSession(); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); transport.sendMessage(msg, msg.getAllRecipients()); transport.close();/*ww w . j a v a 2 s.co m*/ server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }