List of usage examples for javax.mail Session getTransport
public Transport getTransport(Address address) throws NoSuchProviderException
From source file:transport.java
public void go(Session session, InternetAddress[] toAddr, InternetAddress from) { Transport trans = null;/*from w w w.j a v a 2 s . c om*/ try { // create a message Message msg = new MimeMessage(session); msg.setFrom(from); msg.setRecipients(Message.RecipientType.TO, toAddr); msg.setSubject("JavaMail APIs transport.java Test"); msg.setSentDate(new Date()); // Date: header msg.setContent(msgText + msgText2, "text/plain"); msg.saveChanges(); // get the smtp transport for the address trans = session.getTransport(toAddr[0]); // register ourselves as listener for ConnectionEvents // and TransportEvents trans.addConnectionListener(this); trans.addTransportListener(this); // connect the transport trans.connect(); // send the message trans.sendMessage(msg, toAddr); // give the EventQueue enough time to fire its events try { Thread.sleep(5); } catch (InterruptedException e) { } } catch (MessagingException mex) { // give the EventQueue enough time to fire its events try { Thread.sleep(5); } catch (InterruptedException e) { } mex.printStackTrace(); System.out.println(); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { System.out.println(" ** Invalid Addresses"); if (invalid != null) { for (int i = 0; i < invalid.length; i++) System.out.println(" " + invalid[i]); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { System.out.println(" ** ValidUnsent Addresses"); if (validUnsent != null) { for (int i = 0; i < validUnsent.length; i++) System.out.println(" " + validUnsent[i]); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { System.out.println(" ** ValidSent Addresses"); if (validSent != null) { for (int i = 0; i < validSent.length; i++) System.out.println(" " + validSent[i]); } } } System.out.println(); if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); } finally { try { // close the transport trans.close(); } catch (MessagingException mex) { /* ignore */ } } }
From source file:org.apache.james.protocols.smtp.AbstractStartTlsSMTPServerTest.java
@Test public void testStartTLSWithJavamail() throws Exception { InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort()); ProtocolServer server = null;//from ww w .j a v a 2 s. co m try { TestMessageHook hook = new TestMessageHook(); server = createServer(createProtocol(hook), address, Encryption.createStartTls(BogusSslContextFactory.getServerContext())); server.bind(); Properties mailProps = new Properties(); mailProps.put("mail.smtp.from", "test@localhost"); mailProps.put("mail.smtp.host", address.getHostName()); mailProps.put("mail.smtp.port", address.getPort()); mailProps.put("mail.smtp.socketFactory.class", BogusSSLSocketFactory.class.getName()); mailProps.put("mail.smtp.socketFactory.fallback", "false"); mailProps.put("mail.smtp.starttls.enable", "true"); Session mailSession = Session.getDefaultInstance(mailProps); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress("test@localhost")); String[] emails = { "valid@localhost" }; Address rcpts[] = new Address[emails.length]; for (int i = 0; i < emails.length; i++) { rcpts[i] = new InternetAddress(emails[i].trim().toLowerCase()); } message.setRecipients(Message.RecipientType.TO, rcpts); message.setSubject("Testmail", "UTF-8"); message.setText("Test....."); SMTPTransport transport = (SMTPTransport) mailSession.getTransport("smtps"); transport.connect(new Socket(address.getHostName(), address.getPort())); transport.sendMessage(message, rcpts); assertEquals(1, hook.getQueued().size()); } finally { if (server != null) { server.unbind(); } } }
From source file:eu.optimis.sm.gui.server.ServiceManagerWebServiceImpl.java
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException { final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = System.getProperties(); props.setProperty("mail.smtps.host", "smtp.gmail.com"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.setProperty("mail.smtps.auth", "true"); props.put("mail.smtps.quitwait", "false"); Session session = Session.getInstance(props, null); final MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(username + "@gmail.com")); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); if (ccEmail.length() > 0) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false)); }// w ww . j a v a 2 s . c o m msg.setSubject(title); msg.setText(message, "utf-8"); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport) session.getTransport("smtps"); t.connect("smtp.gmail.com", username, password); t.sendMessage(msg, msg.getAllRecipients()); t.close(); }
From source file:com.fstx.stdlib.common.messages.MailSenderImpl.java
/** * @see com.ess.messages.MailSender#send() *//*www.java 2 s. c o m*/ public boolean send() { try { // 2005-11-27 RSC always requires authentication. Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", host.getAddress()); /* * 2005-11-27 RSC * Since webmail.us is starting to make other ports available * as Comcast blocks port 25. */ props.put("mail.smtp.port", host.getPort()); Session s = Session.getInstance(props, null); MimeMessage messageOut = new MimeMessage(s); InternetAddress fromOut = new InternetAddress(from.getAddress()); //reid 2004-12-20 fromOut.setPersonal(from.getName()); messageOut.setFrom(fromOut); InternetAddress toOut = new InternetAddress(this.to.getAddress()); //reid 2004-12-20 toOut.setPersonal(to.getName()); messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut); messageOut.setSubject(message.getSubject()); messageOut.setText(message.getMessage()); if (host.useAuthentication()) { Transport transport = s.getTransport("smtp"); transport.connect(host.getAddress(), host.getUsername(), host.getPassword()); transport.sendMessage(messageOut, messageOut.getAllRecipients()); transport.close(); } else { Transport.send(messageOut); } } catch (Exception e) { log.info("\n\nMailSenderIMPL3: " + host.getAddress()); e.printStackTrace(); throw new RuntimeException(e); } 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 ww w. j a v a 2 s . c o m 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:org.blue.star.plugins.send_mail.java
public boolean execute_check() { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); if (smtpAuth) { props.put("mail.smtp.auth", "true"); }//from w w w .ja v a 2s .co m Session session = Session.getInstance(props, null); SMTPTransport transport = null; // if (debug) // session.setDebug(true); // construct the message try { Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (subject != null) msg.setSubject(subject); msg.setHeader("X-Mailer", "blue-send-mail"); msg.setSentDate(new Date()); msg.setText(message.replace("\\n", "\n").replace("\\t", "\t")); transport = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp"); if (smtpAuth) transport.connect(smtpServer, smtpUser, smtpPass); else transport.connect(); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (MessagingException mE) { mE.printStackTrace(); this.state = common_h.STATE_CRITICAL; this.text = mE.getMessage(); return false; } finally { try { transport.close(); } catch (Exception e) { } } state = common_h.STATE_OK; text = "Message Sent!"; return true; }
From source file:tsuboneSystem.original.manager.MailManager.java
/** * ?//from w w w. java2 s . co m * @return */ public boolean sendMail() { //???TRUE if (!check()) { return false; } Properties objPrp = new Properties(); objPrp.setProperty("mail.smtp.host", "smtp.gmail.com"); objPrp.setProperty("mail.smtp.port", "465"); objPrp.setProperty("mail.smtp.auth", "true"); // objPrp.setProperty("mail.smtp.connectiontimeout", "5000"); objPrp.setProperty("mail.smtp.timeout", "5000"); //???????????JavaMail?Message-ID????? objPrp.setProperty("mail.user", "kagucho.net@gmail.com"); objPrp.setProperty("mail.host", "smtp.gmail.com"); //???????? objPrp.setProperty("mail.debug", "true"); // SSL objPrp.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); objPrp.setProperty("mail.smtp.socketFactory.fallback", "false"); objPrp.setProperty("mail.smtp.socketFactory.port", "465"); String address = ConfigUtil.getConfig("mail.address"); String pw = ConfigUtil.getConfig("mail.pw"); // Session session = Session.getInstance(objPrp, new PlainAuthenticator(address, pw)); // ?? MimeMessage objMsg = new MimeMessage(session); try { // ? objMsg.setFrom(new InternetAddress(address, displayName)); // ?? objMsg.setSubject(title, encoding); // ?TO????CCBCC? objMsg.setRecipients(Message.RecipientType.BCC, getToAddress()); // objMsg.setText(getContent(), encoding); // ? SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); try { t.connect("smtp.gmail.com", address, pw); t.sendMessage(objMsg, objMsg.getAllRecipients()); } finally { t.close(); } return false; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return true; } catch (MessagingException e) { e.printStackTrace(); return true; } }
From source file:net.spfbl.core.Analise.java
private static Object getResponseSMTP(String host, int port, int timeout) { try {/*w w w. ja va 2s . c o m*/ Properties props = new Properties(); props.put("mail.smtp.starttls.enable", "false"); props.put("mail.smtp.auth", "false"); props.put("mail.smtp.timeout", Integer.toString(timeout)); props.put("mail.smtp.connectiontimeout", "3000"); Session session = Session.getInstance(props, null); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); try { transport.setLocalHost(Core.getHostname()); transport.connect(host, port, null, null); String response = transport.getLastServerResponse(); int beginIndex = 4; int endIndex; for (endIndex = beginIndex; endIndex < response.length(); endIndex++) { if (response.charAt(endIndex) == ' ') { break; } else if (response.charAt(endIndex) == '\n') { break; } } String helo = response.substring(beginIndex, endIndex); if (helo.contains(".") && Domain.isHostname(helo)) { return Domain.normalizeHostname(helo, true); } else { return null; } } finally { if (transport.isConnected()) { transport.close(); } } } catch (MailConnectException ex) { if (ex.getMessage().contains("timeout -1")) { return Status.CLOSED; } else { return Status.TIMEOUT; } } catch (MessagingException ex) { // if (ex.getMessage().containsExact("TLS")) { // return Status.NOTLS; // } else { return Status.UNAVAILABLE; // } } catch (Exception ex) { Server.logError(ex); return null; } }
From source file:mx.uatx.tesis.managebeans.RecuperarCuentaMB.java
public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception { String passwordDesencriptada = Desencriptar(password2); try {/*from w w w. j a v a 2s . co 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 ha recibido tu solicitud. " + "\n Los siguientes son tus datos para acceder:" + "\n Correo: " + corre + "\n Password: " + passwordDesencriptada + ""); // 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:common.email.MailServiceImpl.java
/** * this method sends email using a given template * @param subject subject of a mail/* w w w.j a v a 2s. co m*/ * @param recipientEmail email receiver adress * @param mail mail text to send * @param from will be set * @return true if send succeed * @throws java.io.FileNotFoundException * @throws java.io.IOException */ protected boolean postMail(String subject, String recipientEmail, String from, String mail) throws IOException { try { Properties props = new Properties(); //props.put("mailHost", mailHost); Session session = Session.getInstance(props); // construct the message javax.mail.Message msg = new javax.mail.internet.MimeMessage(session); if (from == null) { msg.setFrom(); } else { try { msg.setFrom(new InternetAddress(from)); } catch (MessagingException ex) { logger.error(ex); } } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); msg.setSubject(subject); msg.setSentDate(new Date()); //msg.setHeader("", user) msg.setDataHandler(new DataHandler(new ByteArrayDataSource(mail, "text/html; charset=UTF-8"))); SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); t.connect(mailHost, user, password); Address[] a = msg.getAllRecipients(); t.sendMessage(msg, a); t.close(); return true; } catch (MessagingException ex) { logger.error(ex); ex.printStackTrace(); return false; } }