List of usage examples for javax.mail Session getTransport
public Transport getTransport(Address address) throws NoSuchProviderException
From source file:com.zimbra.cs.util.SmtpInject.java
public static void main(String[] args) { CliUtil.toolSetup();//from w w w . j a va 2 s .co m CommandLine cl = parseArgs(args); if (cl.hasOption("h")) { usage(null); } String file = null; if (!cl.hasOption("f")) { usage("no file specified"); } else { file = cl.getOptionValue("f"); } try { ByteUtil.getContent(new File(file)); } catch (IOException ioe) { usage(ioe.getMessage()); } String host = null; if (!cl.hasOption("a")) { usage("no smtp server specified"); } else { host = cl.getOptionValue("a"); } String sender = null; if (!cl.hasOption("s")) { usage("no sender specified"); } else { sender = cl.getOptionValue("s"); } String recipient = null; if (!cl.hasOption("r")) { usage("no recipient specified"); } else { recipient = cl.getOptionValue("r"); } boolean trace = false; if (cl.hasOption("T")) { trace = true; } boolean tls = false; if (cl.hasOption("t")) { tls = true; } boolean auth = false; String user = null; String password = null; if (cl.hasOption("A")) { auth = true; if (!cl.hasOption("u")) { usage("auth enabled, no user specified"); } else { user = cl.getOptionValue("u"); } if (!cl.hasOption("p")) { usage("auth enabled, no password specified"); } else { password = cl.getOptionValue("p"); } } if (cl.hasOption("v")) { mLog.info("SMTP server: " + host); mLog.info("Sender: " + sender); mLog.info("Recipient: " + recipient); mLog.info("File: " + file); mLog.info("TLS: " + tls); mLog.info("Auth: " + auth); if (auth) { mLog.info("User: " + user); char[] dummyPassword = new char[password.length()]; Arrays.fill(dummyPassword, '*'); mLog.info("Password: " + new String(dummyPassword)); } } Properties props = System.getProperties(); props.put("mail.smtp.host", host); if (auth) { props.put("mail.smtp.auth", "true"); } else { props.put("mail.smtp.auth", "false"); } if (tls) { props.put("mail.smtp.starttls.enable", "true"); } else { props.put("mail.smtp.starttls.enable", "false"); } // Disable certificate checking so we can test against // self-signed certificates props.put("mail.smtp.ssl.socketFactory", SocketFactories.dummySSLSocketFactory()); Session session = Session.getInstance(props, null); session.setDebug(trace); try { // create a message MimeMessage msg = new ZMimeMessage(session, new ZSharedFileInputStream(file)); InternetAddress[] address = { new JavaMailInternetAddress(recipient) }; msg.setFrom(new JavaMailInternetAddress(sender)); // attach the file to the message Transport transport = session.getTransport("smtp"); transport.connect(null, user, password); transport.sendMessage(msg, address); } catch (MessagingException mex) { mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); } System.exit(1); } }
From source file:smtpsend.java
public static void main(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;/*from w w w . ja v a 2 s .c o m*/ String mailer = "smtpsend"; String file = null; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; boolean verbose = false; boolean auth = false; boolean ssl = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-a")) { file = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-A")) { auth = true; } else if (argv[optind].equals("-S")) { ssl = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]"); System.out.println("\t[-v] [-A] [-S] [address]"); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); if (mailhost != null) props.put("mail.smtp.host", mailhost); if (auth) props.put("mail.smtp.auth", "true"); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message 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 (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); String text = collect(in); if (file != null) { // Attach the specified file. // We need a multipart message to hold the attachment. MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(text); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.attachFile(file); MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); } else { // If the desired charset is known, you can use // setText(text, charset) msg.setText(text); } msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off /* * The simple way to send a message is this: * * Transport.send(msg); * * But we're going to use some SMTP-specific features for demonstration * purposes so we need to manage the Transport object explicitly. */ SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp"); try { if (auth) t.connect(mailhost, user, password); else t.connect(); t.sendMessage(msg, msg.getAllRecipients()); } finally { if (verbose) System.out.println("Response: " + t.getLastServerResponse()); t.close(); } System.out.println("\nMail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { if (e instanceof SendFailedException) { MessagingException sfe = (MessagingException) e; if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; System.out.println("SMTP SEND FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else { if (verbose) System.out.println("Send failed: " + sfe.toString()); } Exception ne; while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) { sfe = (MessagingException) ne; if (sfe instanceof SMTPAddressFailedException) { SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe; System.out.println("ADDRESS FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else if (sfe instanceof SMTPAddressSucceededException) { System.out.println("ADDRESS SUCCEEDED:"); SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe; if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } } } else { System.out.println("Got Exception: " + e); if (verbose) e.printStackTrace(); } } }
From source file:smtpsend.java
/** * Example of how to extend the SMTPTransport class. * This example illustrates how to issue the XACT * command before the SMTPTransport issues the DATA * command.// ww w. jav a2 s. c o m * public static class SMTPExtension extends SMTPTransport { public SMTPExtension(Session session, URLName url) { super(session, url); // to check that we're being used System.out.println("SMTPExtension: constructed"); } protected synchronized OutputStream data() throws MessagingException { if (supportsExtension("XACCOUNTING")) issueCommand("XACT", 250); return super.data(); } } */ public static void main(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null; String mailer = "smtpsend"; String file = null; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; boolean verbose = false; boolean auth = false; String prot = "smtp"; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; /* * Process command line arguments. */ for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-a")) { file = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-A")) { auth = true; } else if (argv[optind].equals("-S")) { prot = "smtps"; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]"); System.out.println("\t[-v] [-A] [-S] [address]"); System.exit(1); } else { break; } } try { /* * Prompt for To and Subject, if not specified. */ if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } /* * Initialize the JavaMail Session. */ Properties props = System.getProperties(); if (mailhost != null) props.put("mail." + prot + ".host", mailhost); if (auth) props.put("mail." + prot + ".auth", "true"); /* * Create a Provider representing our extended SMTP transport * and set the property to use our provider. * Provider p = new Provider(Provider.Type.TRANSPORT, prot, "smtpsend$SMTPExtension", "JavaMail demo", "no version"); props.put("mail." + prot + ".class", "smtpsend$SMTPExtension"); */ // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); /* * Register our extended SMTP transport. * session.addProvider(p); */ /* * Construct the message and send it. */ 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 (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); String text = collect(in); if (file != null) { // Attach the specified file. // We need a multipart message to hold the attachment. MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(text); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.attachFile(file); MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); } else { // If the desired charset is known, you can use // setText(text, charset) msg.setText(text); } msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off /* * The simple way to send a message is this: * Transport.send(msg); * * But we're going to use some SMTP-specific features for * demonstration purposes so we need to manage the Transport * object explicitly. */ SMTPTransport t = (SMTPTransport) session.getTransport(prot); try { if (auth) t.connect(mailhost, user, password); else t.connect(); t.sendMessage(msg, msg.getAllRecipients()); } finally { if (verbose) System.out.println("Response: " + t.getLastServerResponse()); t.close(); } System.out.println("\nMail was sent successfully."); /* * Save a copy of the message, if requested. */ if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { /* * Handle SMTP-specific exceptions. */ if (e instanceof SendFailedException) { MessagingException sfe = (MessagingException) e; if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; System.out.println("SMTP SEND FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else { if (verbose) System.out.println("Send failed: " + sfe.toString()); } Exception ne; while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) { sfe = (MessagingException) ne; if (sfe instanceof SMTPAddressFailedException) { SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe; System.out.println("ADDRESS FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else if (sfe instanceof SMTPAddressSucceededException) { System.out.println("ADDRESS SUCCEEDED:"); SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe; if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } } } else { System.out.println("Got Exception: " + e); if (verbose) e.printStackTrace(); } } }
From source file:lucee.runtime.net.mail.SMTPVerifier.java
private static boolean _verify(String host, String username, String password, int port) throws MessagingException { boolean hasAuth = !StringUtil.isEmpty(username); Properties props = new Properties(); props.put("mail.smtp.host", host); if (hasAuth)// ww w .j a v a 2 s . c o m props.put("mail.smtp.auth", "true"); if (hasAuth) props.put("mail.smtp.user", username); if (hasAuth) props.put("mail.transport.connect-timeout", "30"); if (port > 0) props.put("mail.smtp.port", String.valueOf(port)); Authenticator auth = null; if (hasAuth) auth = new DefaultAuthenticator(username, password); Session session = Session.getInstance(props, auth); Transport transport = session.getTransport("smtp"); if (hasAuth) transport.connect(host, username, password); else transport.connect(); boolean rtn = transport.isConnected(); transport.close(); return rtn; }
From source file:ee.cyber.licensing.service.MailService.java
private static void sendMail(String email, String password, String host, Session getMailSession, MimeMessage mailMessage) throws MessagingException { Transport transport = getMailSession.getTransport("smtp"); // if you have 2FA enabled then provide App Specific Password transport.connect(host, email, password); transport.sendMessage(mailMessage, mailMessage.getAllRecipients()); transport.close();/*from w w w . ja v a 2s. c om*/ logger.info("6th ===> Email Sent Successfully With Image Attachment"); logger.info("7th ===> generateAndSendEmail() ended"); }
From source file:org.bml.util.mail.MailUtils.java
/** * Simple mail utility/* w ww . ja v a 2 s.c o m*/ * @param sendToAdresses email addresses to send the mail to * @param emailSubjectLine the subject of the email. * @param emailBody The body of the mail * @param smtpHost the smtp host * @param sender the mail address that is the sender * @param smtpPassword the password for the sender * @param smtpPort the port to contact the smtp server on * @return boolean true on success and false on error */ public static boolean sendMail(final String[] sendToAdresses, final String emailSubjectLine, final String emailBody, final String smtpHost, String sender, String smtpPassword, final int smtpPort) { if ((sendToAdresses == null) || (sendToAdresses.length == 0)) { return false; } if ((emailSubjectLine == null) || (emailBody == null)) { return false; } try { Address[] addresses = new Address[sendToAdresses.length]; for (int i = 0; i < sendToAdresses.length; i++) { addresses[i] = new InternetAddress(sendToAdresses[i]); } Properties props = System.getProperties(); props.setProperty("mail.smtp.host", smtpHost); props.setProperty("mail.smtp.localhost", smtpHost); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.port", String.valueOf(smtpPort)); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getDefaultInstance(props, null); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); message.setRecipients(Message.RecipientType.TO, addresses); message.setSubject(emailSubjectLine); message.setContent(emailBody, "text/plain"); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(smtpHost, sender, smtpPassword); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error("Error occured while sending mail.", t); } return false; } return true; }
From source file:pl.umk.mat.zawodyweb.email.EmailSender.java
public static void send(String address, String subject, String text) { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(props); try {/*from ww w. j a va 2 s . c o m*/ Address[] addresses = InternetAddress.parse(address); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(addressFrom)); message.setRecipients(Message.RecipientType.TO, addresses); message.setSubject(subjectPrefix + subject); message.setSentDate(new Date()); message.setText(text); Transport transport = session.getTransport("smtp"); transport.connect(smtpHost, smtpPort, smtpUser, smtpPassword); transport.sendMessage(message, addresses); transport.close(); } catch (MessagingException ex) { log.error(ex); } }
From source file:com.liferay.util.mail.MailEngine.java
private static void _sendMessage(Session session, Message msg) throws MessagingException { boolean smtpAuth = GetterUtil.getBoolean(session.getProperty("mail.smtp.auth"), false); String smtpHost = session.getProperty("mail.smtp.host"); String user = session.getProperty("mail.smtp.user"); String password = session.getProperty("mail.smtp.password"); if (smtpAuth && Validator.isNotNull(user) && Validator.isNotNull(password)) { Transport tr = session.getTransport("smtp"); tr.connect(smtpHost, user, password); tr.sendMessage(msg, msg.getAllRecipients()); tr.close();//from w ww . j av a 2 s. c o m } else { Transport.send(msg); } }
From source file:quickforms.sme.UseFulMethods.java
static public void sendEmail(String d_email, String pwd, String m_to, String m_subject, String message) throws Exception { final String from = d_email; final String password = pwd; class SMTPAuthenticator extends Authenticator { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); }/*from www. j a v a 2 s . com*/ } //String d_uname = "email"; //String d_password = "password"; String d_host = "smtp.gmail.com"; String d_port = "465"; //465,587 Properties props = new Properties(); props.put("mail.smtp.user", from); props.put("mail.smtp.host", d_host); props.put("mail.smtp.port", d_port); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.debug", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.socketFactory.port", d_port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); SMTPAuthenticator auth = new SMTPAuthenticator(); Session session = Session.getInstance(props, auth); session.setDebug(true); MimeMessage msg = new MimeMessage(session); //msg.setText(message); // Send the actual HTML message, as big as you like msg.setContent(message, "text/html"); msg.setSubject(m_subject); msg.setFrom(new InternetAddress(from)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to)); Transport transport = session.getTransport("smtps"); transport.connect(d_host, 465, from, password); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); }
From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * return the transport object of the SMTP session * * @return the transport object of the SMTP session * @param session the SMTP session//from w ww.j a v a2 s .c o m * @throws NoSuchProviderException If the provider is not found */ protected static Transport getTransport(Session session) throws NoSuchProviderException { return session.getTransport(SMTP); }