List of usage examples for javax.mail Session getDefaultInstance
public static synchronized Session getDefaultInstance(Properties props, Authenticator authenticator)
From source file:gt.dakaik.common.Common.java
public static MimeMessage createEmail(String to, String subject, String bodyText) throws MessagingException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); email.setFrom(new InternetAddress(sendMailFrom)); email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); email.setSubject(subject);/*from ww w. ja v a 2 s. co m*/ email.setText(bodyText); return email; }
From source file:com.enonic.esl.net.Mail.java
/** * <p/> Send the mail. The SMTP host is contacted and the mail is sent according to the parameters set. </p> <p/> If it fails, it is * considered a runtime exception. Note that this doesn't make it very failsafe, so care should be taken when one wants fault tolerance. * One solution could be to catch the exception thrown. Another solution could be to use the JavaMail API directly. </p> *//*from w w w .jav a2 s.c om*/ public void send() throws ESLException { // smtp server Properties smtpProperties = new Properties(); if (smtpHost != null) { smtpProperties.put("mail.smtp.host", smtpHost); System.setProperty("mail.smtp.host", smtpHost); } else { smtpProperties.put("mail.smtp.host", DEFAULT_SMTPHOST); System.setProperty("mail.smtp.host", DEFAULT_SMTPHOST); } Session session = Session.getDefaultInstance(smtpProperties, null); try { // create message Message msg = new MimeMessage(session); // set from address InternetAddress addressFrom = new InternetAddress(); if (from_email != null) { addressFrom.setAddress(from_email); } if (from_name != null) { addressFrom.setPersonal(from_name, ENCODING); } ((MimeMessage) msg).setFrom(addressFrom); if ((to.size() == 0 && bcc.size() == 0) || subject == null || (message == null && htmlMessage == null)) { LOG.error("Missing data. Unable to send mail."); throw new ESLException("Missing data. Unable to send mail."); } // set to: for (int i = 0; i < to.size(); ++i) { String[] recipient = to.get(i); InternetAddress addressTo = new InternetAddress(recipient[1]); if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.TO, addressTo); } // set bcc: for (int i = 0; i < bcc.size(); ++i) { String[] recipient = bcc.get(i); InternetAddress addressTo = null; try { addressTo = new InternetAddress(recipient[1]); } catch (Exception e) { System.err.println("exception on address: " + recipient[1]); continue; } if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.BCC, addressTo); } // set cc: for (int i = 0; i < cc.size(); ++i) { String[] recipient = cc.get(i); InternetAddress addressTo = new InternetAddress(recipient[1]); if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.CC, addressTo); } // Setting subject and content type ((MimeMessage) msg).setSubject(subject, ENCODING); if (message != null) { message = RegexpUtil.substituteAll("\\\\n", "\n", message); } // if there are any attachments, treat this as a multipart message. if (attachments.size() > 0) { BodyPart messageBodyPart = new MimeBodyPart(); if (message != null) { ((MimeBodyPart) messageBodyPart).setText(message, ENCODING); } else { DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(htmlMessage, "text/html", ENCODING)); ((MimeBodyPart) messageBodyPart).setDataHandler(dataHandler); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // add all attachments for (int i = 0; i < attachments.size(); ++i) { Object obj = attachments.get(i); if (obj instanceof String) { System.err.println("attachment is String"); messageBodyPart = new MimeBodyPart(); ((MimeBodyPart) messageBodyPart).setText((String) obj, ENCODING); multipart.addBodyPart(messageBodyPart); } else if (obj instanceof File) { messageBodyPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource((File) obj); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setFileName(fds.getName()); multipart.addBodyPart(messageBodyPart); } else if (obj instanceof FileItem) { FileItem fileItem = (FileItem) obj; messageBodyPart = new MimeBodyPart(); FileItemDataSource fds = new FileItemDataSource(fileItem); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setFileName(fds.getName()); multipart.addBodyPart(messageBodyPart); } else { // byte array messageBodyPart = new MimeBodyPart(); ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) obj, "text/html", ENCODING); messageBodyPart.setDataHandler(new DataHandler(bads)); messageBodyPart.setFileName(bads.getName()); multipart.addBodyPart(messageBodyPart); } } msg.setContent(multipart); } else { if (message != null) { ((MimeMessage) msg).setText(message, ENCODING); } else { DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(htmlMessage, "text/html", ENCODING)); ((MimeMessage) msg).setDataHandler(dataHandler); } } // send message Transport.send(msg); } catch (AddressException e) { String MESSAGE_30 = "Error in email address: " + e.getMessage(); LOG.warn(MESSAGE_30); throw new ESLException(MESSAGE_30, e); } catch (UnsupportedEncodingException e) { String MESSAGE_40 = "Unsupported encoding: " + e.getMessage(); LOG.error(MESSAGE_40, e); throw new ESLException(MESSAGE_40, e); } catch (SendFailedException sfe) { Throwable t = null; Exception e = sfe.getNextException(); while (e != null) { t = e; if (t instanceof SendFailedException) { e = ((SendFailedException) e).getNextException(); } else { e = null; } } if (t != null) { String MESSAGE_50 = "Error sending mail: " + t.getMessage(); throw new ESLException(MESSAGE_50, t); } else { String MESSAGE_50 = "Error sending mail: " + sfe.getMessage(); throw new ESLException(MESSAGE_50, sfe); } } catch (MessagingException e) { String MESSAGE_50 = "Error sending mail: " + e.getMessage(); LOG.error(MESSAGE_50, e); throw new ESLException(MESSAGE_50, e); } }
From source file:ru.org.linux.util.EmailService.java
public void sendEmail(String nick, String email, boolean isNew) throws MessagingException { StringBuilder text = new StringBuilder(); text.append("?!\n\n"); if (isNew) {/* ww w .j a v a 2 s. c o m*/ text.append( "\t? ? http://www.linux.org.ru/ ?? ?? ?,\n"); } else { text.append( "\t? ? http://www.linux.org.ru/ ?? ?,\n"); } text.append(" ? ? (e-mail).\n\n"); text.append( " ? ? ? ?: '"); text.append(nick); text.append("'\n\n"); text.append( "? , - ? ? ?!\n\n"); if (isNew) { text.append( "? ??? ? http://www.linux.org.ru/,\n"); text.append( " ? ? ? ? ?.\n\n"); } else { text.append( "? ? ? ? http://www.linux.org.ru/,\n"); text.append(" ? ? .\n\n"); } String regcode = User.getActivationCode(configuration.getSecret(), nick, email); text.append( "? ?? http://www.linux.org.ru/activate.jsp\n\n"); text.append(" : ").append(regcode).append("\n\n"); text.append(" ?!\n"); Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); Session mailSession = Session.getDefaultInstance(props, null); MimeMessage emailMessage = new MimeMessage(mailSession); emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru")); emailMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email)); emailMessage.setSubject("Linux.org.ru registration"); emailMessage.setSentDate(new Date()); emailMessage.setText(text.toString(), "UTF-8"); Transport.send(emailMessage); }
From source file:com.formkiq.core.service.notification.MailSenderServiceTest.java
/** * testLoadMailProperties01()./*from w w w . j a v a 2 s. com*/ * @throws Exception Exception */ @Test public void testLoadMailProperties01() throws Exception { // given String ls = System.getProperty("line.separator"); String source = "mail.host=smtp.gmail.com" + ls + "mail.port=587" + ls + "mail.username=test@formkiq.com" + ls + "mail.password=test" + ls + "mail.smtp.auth=true" + ls + "mail.smtp.starttls.enable=true" + ls + "mail.smtp.quitwait=false"; InputStream in = IOUtils.toInputStream(source, "UTF-8"); Properties prop = new Properties(); prop.load(in); // when Session se = Session.getDefaultInstance(prop, null); Provider prov = se.getProvider("smtp"); Class<?> clazz = Class.forName(prov.getClassName()); // then assertNotNull(clazz); in.close(); }
From source file:org.apache.roller.weblogger.business.MailProvider.java
public MailProvider() throws StartupException { String connectionTypeString = WebloggerConfig.getProperty("mail.configurationType"); if ("properties".equals(connectionTypeString)) { type = ConfigurationType.MAIL_PROPERTIES; }/*from www . ja va 2 s. c o m*/ jndiName = WebloggerConfig.getProperty("mail.jndi.name"); mailHostname = WebloggerConfig.getProperty("mail.hostname"); mailUsername = WebloggerConfig.getProperty("mail.username"); mailPassword = WebloggerConfig.getProperty("mail.password"); try { String portString = WebloggerConfig.getProperty("mail.port"); if (portString != null) { mailPort = Integer.parseInt(portString); } } catch (Throwable t) { log.warn("mail server port not a valid integer, ignoring"); } // init and connect now so we fail early if (type == ConfigurationType.JNDI_NAME) { String name = "java:comp/env/" + jndiName; try { Context ctx = (Context) new InitialContext(); session = (Session) ctx.lookup(name); } catch (NamingException ex) { throw new StartupException("ERROR looking up mail-session with JNDI name: " + name); } } else { Properties props = new Properties(); props.put("mail.smtp.host", mailHostname); if (mailUsername != null && mailPassword != null) { props.put("mail.smtp.auth", "true"); } if (mailPort != -1) { props.put("mail.smtp.port", "" + mailPort); } session = Session.getDefaultInstance(props, null); } try { Transport transport = getTransport(); transport.close(); } catch (Throwable t) { throw new StartupException("ERROR connecting to mail server", t); } }
From source file:com.sun.socialsite.business.MailProvider.java
public MailProvider() throws StartupException { String connectionTypeString = Config.getProperty("mail.configurationType"); if ("properties".equals(connectionTypeString)) { type = ConfigurationType.MAIL_PROPERTIES; }//from w w w . j av a 2 s.c o m jndiName = Config.getProperty("mail.jndi.name"); mailHostname = Config.getProperty("mail.hostname"); mailUsername = Config.getProperty("mail.username"); mailPassword = Config.getProperty("mail.password"); try { String portString = Config.getProperty("mail.port"); if (portString != null) { mailPort = Integer.parseInt(portString); } } catch (Throwable t) { log.warn("mail server port not a valid integer, ignoring"); } // init and connect now so we fail early if (type == ConfigurationType.JNDI_NAME) { String name = "java:comp/env/" + jndiName; try { Context ctx = (Context) new InitialContext(); session = (Session) ctx.lookup(name); } catch (NamingException ex) { throw new StartupException("ERROR looking up mail-session with JNDI name: " + name); } } else { Properties props = new Properties(); props.put("mail.smtp.host", mailHostname); if (mailUsername != null && mailPassword != null) { props.put("mail.smtp.auth", "true"); } if (mailPort != -1) { props.put("mail.smtp.port", "" + mailPort); } session = Session.getDefaultInstance(props, null); } try { Transport transport = getTransport(); transport.close(); } catch (Throwable t) { throw new StartupException("ERROR connecting to mail server", t); } }
From source file:eu.scape_project.planning.application.Feedback.java
/** * Method responsible for sending feedback per mail. * /*w w w.j a v a 2 s . c om*/ * @param userEmail * email address of the user. * @param userComments * comments from the user * @param location * the location of the application where the error occurred * @param applicationName * the name of the application * @throws MailException * if the feedback could not be sent */ public void sendFeedback(String userEmail, String userComments, String location, String applicationName) throws MailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(config.getString("mail.feedback"))); message.setSubject("[" + applicationName + "] from " + location); StringBuilder builder = new StringBuilder(); builder.append("Date: ").append(dateFormat.format(new Date())).append("\n\n"); // User info if (user == null) { builder.append("No user available.\n\n"); } else { builder.append("User: ").append(user.getUsername()).append("\n"); if (user.getUserGroup() != null) { builder.append("Group: ").append(user.getUserGroup().getName()).append("\n"); } } builder.append("UserMail: ").append(userEmail).append("\n\n"); // Comments builder.append("Comments:\n"); builder.append(SEPARATOR_LINE); builder.append(userComments).append("\n"); builder.append(SEPARATOR_LINE).append("\n"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Feedback mail sent successfully to {}", config.getString("mail.feedback")); } catch (MessagingException e) { log.error("Error sending feedback mail to {}", config.getString("mail.feedback"), e); throw new MailException("Error sending feedback mail to " + config.getString("mail.feedback"), e); } }
From source file:Sender2.java
private void finish() { // Create the Session object session = Session.getDefaultInstance(props, null); // session.setDebug(true); // Verbose! // create a message mesg = new MimeMessage(session); }
From source file:com.seleniumtests.connectors.mails.ImapClient.java
/** * connect to folder/* w w w. j ava 2s . co m*/ * @param host server address * @param username login for server * @param password password for server * @throws MessagingException */ private void connect(String host, String username, String password) throws MessagingException { // Create empty properties Properties props = new Properties(); // Get session Session session = Session.getDefaultInstance(props, null); // Get the store store = session.getStore("imap"); store.connect(host, imapPort, username, password); }
From source file:SendMime.java
/** Do the work: send the mail to the SMTP server. */ public void doSend() throws IOException, MessagingException { // Create the Session object session = Session.getDefaultInstance(null, null); session.setDebug(true); // Verbose! try {/*from w ww. j av a2 s . com*/ // create a message mesg = new MimeMessage(session); // From Address - this should come from a Properties... mesg.setFrom(new InternetAddress("nobody@host.domain")); // TO Address InternetAddress toAddress = new InternetAddress(message_recip); mesg.addRecipient(Message.RecipientType.TO, toAddress); // CC Address InternetAddress ccAddress = new InternetAddress(message_cc); mesg.addRecipient(Message.RecipientType.CC, ccAddress); // The Subject mesg.setSubject(message_subject); // Now the message body. Multipart mp = new MimeMultipart(); BodyPart textPart = new MimeBodyPart(); textPart.setText(message_body); // sets type to "text/plain" BodyPart pixPart = new MimeBodyPart(); pixPart.setContent(html_data, "text/html"); // Collect the Parts into the MultiPart mp.addBodyPart(textPart); mp.addBodyPart(pixPart); // Put the MultiPart into the Message mesg.setContent(mp); // Finally, send the message! Transport.send(mesg); } catch (MessagingException ex) { System.err.println(ex); ex.printStackTrace(System.err); } }