List of usage examples for javax.mail Session getTransport
public Transport getTransport(Address address) throws NoSuchProviderException
From source file:org.artifactory.mail.MailServiceImpl.java
/** * Send an e-mail message//w w w .j av a2s . c o m * * @param recipients Recipients of the message that will be sent * @param subject The subject of the message * @param body The body of the message * @param config A mail server configuration to use * @throws Exception */ @Override public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config) throws EmailException { verifyParameters(recipients, config); if (!config.isEnabled()) { log.debug("Ignoring requested mail delivery. The given configuration is disabled."); return; } boolean debugEnabled = log.isDebugEnabled(); Properties properties = new Properties(); properties.put("mail.smtp.host", config.getHost()); properties.put("mail.smtp.port", Integer.toString(config.getPort())); properties.put("mail.smtp.quitwait", "false"); //Default protocol String protocol = "smtp"; //Enable TLS if set if (config.isUseTls()) { properties.put("mail.smtp.starttls.enable", "true"); } //Enable SSL if set boolean useSsl = config.isUseSsl(); if (useSsl) { properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort())); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); //Requires special protocol protocol = "smtps"; } //Set debug property if enabled by the logger properties.put("mail.debug", debugEnabled); Authenticator authenticator = null; if (!StringUtils.isEmpty(config.getUsername())) { properties.put("mail.smtp.auth", "true"); authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getUsername(), config.getPassword()); } }; } Session session = Session.getInstance(properties, authenticator); Message message = new MimeMessage(session); String subjectPrefix = config.getSubjectPrefix(); String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject; try { message.setSubject(fullSubject); if (!StringUtils.isEmpty(config.getFrom())) { InternetAddress addressFrom = new InternetAddress(config.getFrom()); message.setFrom(addressFrom); } InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } message.addRecipients(Message.RecipientType.TO, addressTo); //Create multi-part message in case we want to add html support Multipart multipart = new MimeMultipart("related"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(body, "text/html"); multipart.addBodyPart(htmlPart); message.setContent(multipart); //Set debug property if enabled by the logger session.setDebug(debugEnabled); //Connect and send Transport transport = session.getTransport(protocol); if (useSsl) { transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword()); } else { transport.connect(); } transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException e) { String em = e.getMessage(); throw new EmailException( "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n", e); } }
From source file:org.libreplan.web.common.ConfigurationController.java
/** * Test E-mail connection.//from w ww.ja v a 2s .c o m * * @param host * the host * @param port * the port * @param username * the username * @param password * the password */ private void testEmailConnection(String host, String port, String username, String password) { Properties props = System.getProperties(); Transport transport = null; try { if ("SMTP".equals(protocolsCombobox.getSelectedItem().getLabel())) { props.setProperty("mail.smtp.port", port); props.setProperty("mail.smtp.host", host); props.setProperty("mail.smtp.connectiontimeout", Integer.toString(3000)); Session session = Session.getInstance(props, null); transport = session.getTransport("smtp"); if ("".equals(username) && "".equals(password)) { transport.connect(); } } else if (STARTTLS_PROTOCOL.equals(protocolsCombobox.getSelectedItem().getLabel())) { props.setProperty("mail.smtps.port", port); props.setProperty("mail.smtps.host", host); props.setProperty("mail.smtps.connectiontimeout", Integer.toString(3000)); Session session = Session.getInstance(props, null); transport = session.getTransport("smtps"); if (!"".equals(username) && password != null) { transport.connect(host, username, password); } } messages.clearMessages(); if (transport != null) { if (transport.isConnected()) { messages.showMessage(Level.INFO, _("Connection successful!")); } else if (!transport.isConnected()) { messages.showMessage(Level.WARNING, _("Connection unsuccessful")); } } } catch (AuthenticationFailedException e) { messages.clearMessages(); messages.showMessage(Level.ERROR, _("Invalid credentials")); } catch (MessagingException e) { LOG.error(e); messages.clearMessages(); messages.showMessage(Level.ERROR, _("Cannot connect")); } catch (Exception e) { LOG.error(e); messages.clearMessages(); messages.showMessage(Level.ERROR, _("Failed to connect")); } }
From source file:org.exist.xquery.modules.mail.SendEmailFunction.java
public Sequence sendEmail(Sequence[] args, Sequence contextSequence) throws XPathException { // was a session handle specified? if (args[0].isEmpty()) { throw (new XPathException(this, "Session handle not specified")); }// w ww. j a v a2 s .c o m // get the Session long sessionHandle = ((IntegerValue) args[0].itemAt(0)).getLong(); Session session = MailModule.retrieveSession(context, sessionHandle); if (session == null) { throw (new XPathException(this, "Invalid Session handle specified")); } try { List<Message> messages = parseInputEmails(session, args[1]); String proto = session.getProperty("mail.transport.protocol"); if (proto == null) proto = "smtp"; Transport t = session.getTransport(proto); try { if (session.getProperty("mail." + proto + ".auth") != null) t.connect(session.getProperty("mail." + proto + ".user"), session.getProperty("mail." + proto + ".password")); for (Message msg : messages) { t.sendMessage(msg, msg.getAllRecipients()); } } finally { t.close(); } return (Sequence.EMPTY_SEQUENCE); } catch (TransformerException te) { throw new XPathException(this, "Could not Transform XHTML Message Body: " + te.getMessage(), te); } catch (MessagingException smtpe) { throw new XPathException(this, "Could not send message(s): " + smtpe.getMessage(), smtpe); } catch (IOException ioe) { throw new XPathException(this, "Attachment in some message could not be prepared: " + ioe.getMessage(), ioe); } catch (Throwable t) { throw new XPathException(this, "Unexpected error from JavaMail layer (Is your message well structured?): " + t.getMessage(), t); } }
From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; message = "Some of the appliances in your house are running inefficient." + "\n" + "Kindly check or replace your appliance " + "\n" + "Check the attachment for details or visit your account"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {//from ww w. j a v a 2 s .c o m mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Energy Board"); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(message); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(name_attach.getText() + ".png"); multipart.addBodyPart(messageBodyPart); mimeMessage.setContent(multipart); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); System.out.println("sent"); transport.close(); } catch (MessagingException me) { } }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * Send an mail containing the error message back to the * user which sent the given message.//from w w w. jav a2s .c o m * * @param m The message which produced an error while handling it. * @param error The error string. */ private void sendErrorMessage(Message m, String error) throws Exception { /* get the SMTP mail server */ SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer(); if (smtpMailServer == null) { log.warn("Failed to send error message as no SMTP server is configured"); return; } /* get system properties */ Properties props = System.getProperties(); /* Setup mail server */ props.put("mail.smtp.host", smtpMailServer.getHostname()); /* get a session */ Session session = Session.getDefaultInstance(props, null); /* create the message */ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom())); String senderEmail = getEmailAddressFromMessage(m); if (senderEmail == "") { throw new Exception("Unknown sender of email."); } message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail)); message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")"); message.setText("An error occurred while handling your message:\n\n " + error + "\n\nPlease contact the administrator to solve the problem.\n"); /* send the message */ Transport tr = session.getTransport("smtp"); if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) { tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword()); } else { int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort()); tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(), smtpMailServer.getPassword()); } message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); }
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"); }/*from w w w.java 2 s . co 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:org.wandora.piccolo.actions.SendEmail.java
public void doAction(User user, javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, Application application) {//from w w w. j av a 2s . co m try { Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); if (subject != null) message.setSubject(subject); if (from != null) message.setFrom(new InternetAddress(from)); Vector<String> recipients = new Vector<String>(); if (recipient != null) { String[] rs = recipient.split(","); String r = null; for (int i = 0; i < rs.length; i++) { r = rs[i]; if (r != null) recipients.add(r); } } MimeMultipart multipart = new MimeMultipart(); Template template = application.getTemplate(emailTemplate, user); HashMap context = new HashMap(); context.put("request", request); context.put("message", message); context.put("recipients", recipients); context.put("emailhelper", new MailHelper()); context.put("multipart", multipart); context.putAll(application.getDefaultContext(user)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); template.process(context, baos); MimeBodyPart mimeBody = new MimeBodyPart(); mimeBody.setContent(new String(baos.toByteArray(), template.getEncoding()), template.getMimeType()); // mimeBody.setContent(baos.toByteArray(),template.getMimeType()); multipart.addBodyPart(mimeBody); message.setContent(multipart); Transport transport = session.getTransport("smtp"); transport.connect(smtpServer, smtpUser, smtpPass); Address[] recipientAddresses = new Address[recipients.size()]; for (int i = 0; i < recipientAddresses.length; i++) { recipientAddresses[i] = new InternetAddress(recipients.elementAt(i)); } transport.sendMessage(message, recipientAddresses); } catch (Exception e) { logger.writelog("WRN", e); } }
From source file:org.sakaiproject.email.impl.BasicEmailService.java
protected void sendMessageAndLog(InternetAddress from, InternetAddress[] to, String subject, Map<RecipientType, InternetAddress[]> headerTo, long start, MimeMessage msg, Session session) throws MessagingException { long preSend = 0; if (M_log.isDebugEnabled()) preSend = System.currentTimeMillis(); if (allowTransport) { msg.saveChanges();/*w ww . jav a2 s.c om*/ Transport transport = session.getTransport(protocol); if (m_smtpUser != null && m_smtpPassword != null) transport.connect(m_smtp, m_smtpUser, m_smtpPassword); else transport.connect(); transport.sendMessage(msg, to); transport.close(); } long end = 0; if (M_log.isDebugEnabled()) end = System.currentTimeMillis(); if (M_log.isInfoEnabled()) { StringBuilder buf = new StringBuilder(); buf.append("Email.sendMail: from: "); buf.append(from); buf.append(" subject: "); buf.append(subject); buf.append(" to:"); for (int i = 0; i < to.length; i++) { buf.append(" "); buf.append(to[i]); } if (headerTo != null) { if (headerTo.containsKey(RecipientType.TO)) { buf.append(" headerTo{to}:"); InternetAddress[] headerToTo = headerTo.get(RecipientType.TO); for (int i = 0; i < headerToTo.length; i++) { buf.append(" "); buf.append(headerToTo[i]); } } if (headerTo.containsKey(RecipientType.CC)) { buf.append(" headerTo{cc}:"); InternetAddress[] headerToCc = headerTo.get(RecipientType.CC); for (int i = 0; i < headerToCc.length; i++) { buf.append(" "); buf.append(headerToCc[i]); } } if (headerTo.containsKey(RecipientType.BCC)) { buf.append(" headerTo{bcc}:"); InternetAddress[] headerToBcc = headerTo.get(RecipientType.BCC); for (int i = 0; i < headerToBcc.length; i++) { buf.append(" "); buf.append(headerToBcc[i]); } } } try { if (msg.getContent() instanceof Multipart) { Multipart parts = (Multipart) msg.getContent(); buf.append(" with ").append(parts.getCount() - 1).append(" attachments"); } } catch (IOException ioe) { } if (M_log.isDebugEnabled()) { buf.append(" time: "); buf.append("" + (end - start)); buf.append(" in send: "); buf.append("" + (end - preSend)); } M_log.info(buf.toString()); } }
From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java
public String sendMail() { try {/*w w w .ja v a 2 s .co m*/ Properties props = new Properties(); // Server if (smtpServer == null || smtpServer.equals("")) { log.info("samigo.email.smtpServer is not set"); smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); if (smtpServer == null || smtpServer.equals("")) { log.info("smtp@org.sakaiproject.email.api.EmailService is not set"); log.error( "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService"); return "error"; } } props.setProperty("mail.smtp.host", smtpServer); // Port if (smtpPort == null || smtpPort.equals("")) { log.warn("samigo.email.smtpPort is not set. The default port 25 will be used."); } else { props.setProperty("mail.smtp.port", smtpPort); } props.put("mail.smtp.sendpartial", "true"); Session session = Session.getInstance(props, null); session.setDebug(true); MimeMessage msg = new MimeMessage(session); InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName); msg.setFrom(fromIA); //msg.addHeaderLine("Subject: " + subject); msg.setSubject(subject, "UTF-8"); String noReplyEmaillAddress = ServerConfigurationService.getString("setup.request", "no-reply@" + ServerConfigurationService.getServerName()); msg.addHeaderLine("To: " + noReplyEmaillAddress); msg.setText(message, "UTF-8"); msg.addHeaderLine("Content-Type: text/html"); ArrayList<InternetAddress> toIAList = new ArrayList<InternetAddress>(); String email = ""; Iterator iter = toEmailAddressList.iterator(); while (iter.hasNext()) { try { email = (String) iter.next(); toIAList.add(new InternetAddress(email)); } catch (AddressException ae) { log.error("invalid email address: " + email); } } InternetAddress[] toIA = new InternetAddress[toIAList.size()]; int count = 0; Iterator iter2 = toIAList.iterator(); while (iter2.hasNext()) { toIA[count++] = (InternetAddress) iter2.next(); } try { Transport transport = session.getTransport("smtp"); msg.saveChanges(); transport.connect(); try { transport.sendMessage(msg, toIA); } catch (SendFailedException e) { log.debug("SendFailedException: " + e); return "error"; } catch (MessagingException e) { log.warn("1st MessagingException: " + e); return "error"; } transport.close(); } catch (MessagingException e) { log.warn("2nd MessagingException:" + e); return "error"; } } catch (UnsupportedEncodingException ue) { log.warn("UnsupportedEncodingException:" + ue); ue.printStackTrace(); } catch (MessagingException me) { log.warn("3rd MessagingException:" + me); return "error"; } return "send"; }
From source file:org.protocoderrunner.apprunner.api.PNetwork.java
@ProtocoderScript @APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "") @APIParam(params = { "url", "function(data)" }) public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings) throws AddressException, MessagingException { if (emailSettings == null) { return;// w w w . ja v a 2 s .co m } // final String host = "smtp.gmail.com"; // final String address = "@gmail.com"; // final String pass = ""; Multipart multiPart; String finalString = ""; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", emailSettings.ttl); props.put("mail.smtp.host", emailSettings.host); props.put("mail.smtp.user", emailSettings.user); props.put("mail.smtp.password", emailSettings.password); props.put("mail.smtp.port", emailSettings.port); props.put("mail.smtp.auth", emailSettings.auth); Log.i("Check", "done pops"); final Session session = Session.getDefaultInstance(props, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain")); final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setDataHandler(handler); Log.i("Check", "done sessions"); multiPart = new MimeMultipart(); InternetAddress toAddress; toAddress = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); Log.i("Check", "added recipient"); message.setSubject(subject); message.setContent(multiPart); message.setText(text); Thread t = new Thread(new Runnable() { @Override public void run() { try { MLog.i("check", "transport"); Transport transport = session.getTransport("smtp"); MLog.i("check", "connecting"); transport.connect(emailSettings.host, emailSettings.user, emailSettings.password); MLog.i("check", "wana send"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); MLog.i("check", "sent"); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }); t.start(); }