List of usage examples for javax.mail Session getInstance
public static Session getInstance(Properties props, Authenticator authenticator)
From source file:org.lf.yydp.service.film.BuyTicketService.java
/** * :?/*from w w w . j a v a2s . co m*/ * @param receiver */ public void sendEmail(String receiver) { Properties p = null; InputStream inputSteam = null; String senter = null; String Subject = null; String Content = null; try { p = new Properties(); inputSteam = BuyTicketService.class.getClassLoader().getResourceAsStream("mail.properties"); p.load(inputSteam); final String uname = p.getProperty("mail.uname"); final String license = p.getProperty("mail.license"); senter = p.getProperty("mail.senter"); Subject = p.getProperty("mail.subject"); Content = p.getProperty("mail.content"); Authenticator authenticator = new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(uname, license); } }; Session session = Session.getInstance(p, authenticator); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(senter)); msg.setRecipient(RecipientType.TO, new InternetAddress(receiver)); msg.setSubject(Subject); msg.setContent(Content, "text/html;charset=utf-8"); Transport.send(msg); } catch (Exception e) { e.printStackTrace(); } finally { try { if (inputSteam != null) { inputSteam.close(); } } catch (Exception e2) { e2.printStackTrace(); } } }
From source file:NotificationMessage.java
static void sendMail(String toUser, Severity s) { // Recipient's email ID needs to be mentioned. //String to = "abhiyank@gmail.com";//change accordingly // Sender's email ID needs to be mentioned String from = "mdtprojectteam16@gmail.com";//change accordingly final String username = "mdtprojectteam16";//change accordingly final String password = "mdtProject16";//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "smtp.gmail.com"; Properties props = new Properties(); 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"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }//from w ww .ja v a2 s .c o m }); try { // Create a default MimeMessage object. javax.mail.Message message1 = new MimeMessage(session); // Set From: header field of the header. message1.setFrom(new InternetAddress(from)); // Set To: header field of the header. message1.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser)); // Set Subject: header field message1.setSubject("Alert Message From Patient"); // Now set the actual message message1.setText(messageMap.get(s)); // Send message Transport.send(message1); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:org.kuali.rice.core.mail.MailSenderFactoryBean.java
@Override protected Object createInstance() throws Exception { // Retrieve "mail.*" properties from the configuration system and construct a Properties object Properties properties = new Properties(); Properties configProps = ConfigContext.getCurrentContextConfig().getProperties(); LOG.debug("createInstance(): collecting mail properties."); for (Object keyObj : configProps.keySet()) { if (keyObj instanceof String) { String key = (String) keyObj; if (key.startsWith(MAIL_PREFIX)) { properties.put(key, configProps.get(key)); }//from w w w . j a v a 2 s.c om } } // Construct an appropriate Java Mail Session // If username and password properties are found, construct a Session with SMTP authentication String username = properties.getProperty(USERNAME_PROPERTY); String password = properties.getProperty(PASSWORD_PROPERTY); if (username != null && password != null) { mailSession = Session.getInstance(properties, new SimpleAuthenticator(username, password)); LOG.info("createInstance(): Initializing mail session using SMTP authentication."); } else { mailSession = Session.getInstance(properties); LOG.info("createInstance(): Initializing mail session. No SMTP authentication."); } // Construct and return a Spring Java Mail Sender JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); LOG.debug("createInstance(): setting SMTP host."); mailSender.setHost(properties.getProperty(HOST_PROPERTY)); if (properties.getProperty(PORT_PROPERTY) != null) { LOG.debug("createInstance(): setting SMTP port."); int smtpPort = Integer.parseInt(properties.getProperty(PORT_PROPERTY).trim()); mailSender.setPort(smtpPort); } String protocol = properties.getProperty(PROTOCOL_PROPERTY); if (StringUtils.isNotBlank(protocol)) { LOG.debug("createInstance(): setting mail transport protocol = " + protocol); mailSender.setProtocol(protocol); } mailSender.setSession(mailSession); LOG.info("createInstance(): Mail Sender Factory Bean initialized."); return mailSender; }
From source file:pmp.springmail.TestDrive.java
void sendEmailViaPlainMail(String text) { Authenticator authenticator = new Authenticator() { @Override/*w w w . j a v a2 s . c om*/ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(USER, PASS); } }; Session session = Session.getInstance(props, authenticator); Message message = new MimeMessage(session); try { message.setFrom(new InternetAddress(FROM)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(TO)); message.setSubject("Plain JavaMail Test"); message.setText(DATE_FORMAT.format(new Date()) + " " + text); Transport.send(message); } catch (Exception e) { System.err.println(e.getClass().getSimpleName() + " " + e.getMessage()); } }
From source file:org.awknet.commons.mail.Mail.java
public void send() throws AddressException, MessagingException, FileNotFoundException, IOException { int count = recipientsTo.size() + recipientsCc.size() + recipientsBcc.size(); if (count == 0) return;//from www .j a v a 2 s .c o m deleteDuplicates(); Properties javaMailProperties = new Properties(); if (fileName.equals("") || fileName == null) fileName = DEFAULT_PROPERTIES_FILE; javaMailProperties.load(getClass().getResourceAsStream(fileName)); final String mailUsername = javaMailProperties.getProperty("mail.autentication.username"); final String mailPassword = javaMailProperties.getProperty("mail.autentication.password"); final String mailFrom = javaMailProperties.getProperty("mail.autentication.mail_from"); Session session = Session.getInstance(javaMailProperties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mailUsername, mailPassword); } }); final MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(mailFrom)); msg.setRecipients(Message.RecipientType.TO, getToRecipientsArray()); msg.setRecipients(Message.RecipientType.CC, getCcRecipientsArray()); msg.setRecipients(Message.RecipientType.BCC, getBccRecipientsArray()); msg.setSentDate(new Date()); msg.setSubject(mailSubject); msg.setText(mailText, "UTF-8", "html"); // msg.setText(mailText); //OLD WAY new Thread(new Runnable() { public void run() { try { Transport.send(msg); Logger.getLogger(Mail.class.getName()).log(Level.INFO, "email was sent successfully!"); } catch (MessagingException ex) { Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, "Cant send email!", ex); } } }).start(); }
From source file:com.meg7.emailer.EmailerManager.java
@Override protected void processCycle(int cycle) { // Do your thing here. final String username = PreferenceUtils.getEmailUsername(mContext); final String password = PreferenceUtils.getEmailPassword(mContext); if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) { // TODO :: Populate some sort of error to UI. return;//from w w w . j a v a2 s. co m } Properties properties = new Properties(); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); MLog.v(TAG, "Session created for :: " + username); final String fromEmail = PreferenceUtils.getFromEmail(mContext); final String fromName = PreferenceUtils.getFromName(mContext); final String subject = PreferenceUtils.getEmailSubject(mContext); final String message = PreferenceUtils.getEmailMessage(mContext); List<String> all = readEmailsFromFile(cycle + ".txt"); List<String> emails; List<Message> messages = new ArrayList<Message>(); int size = all.size(); int messagesCount = (int) Math.ceil(size / (MAX_RECIPIENTS_PER_EMAIL * 1d)); MLog.v(TAG, "Emails :: " + size + ", messages count :: " + messagesCount); MLog.v(TAG, "Creating messages"); for (int i = 0; i < messagesCount; i++) { try { emails = all.subList(i * MAX_RECIPIENTS_PER_EMAIL, Math.min(i * MAX_RECIPIENTS_PER_EMAIL + MAX_RECIPIENTS_PER_EMAIL, size)); messages.add(createMessage(emails, fromEmail, fromName, subject, message, session)); } catch (Exception e) { MLog.e(TAG, e.toString()); } } sendMessages(messages); // Reschedule the alarm if (getCyclesProcessedTodaySoFar() < EmailerManager.MAX_TASKS_PER_DAY) { Scheduler.scheduleNextWake(mContext); } else { Scheduler.scheduleNextWake(mContext, Constants.THRESHOLD_DAY); resetCyclesProcessedTodaySoFar(); } }
From source file:com.fsrin.menumine.common.message.MailSenderImpl.java
/** * @see com.ess.messages.MailSender#send() *//* www .j ava 2 s . co m*/ public boolean send() { try { Properties props = new Properties(); props.put("mail.smtp.host", host.getAddress()); if (host.useAuthentication()) { props.put("mail.smtp.auth", "true"); } Session s = Session.getInstance(props, null); s.setDebug(true); // PasswordAuthentication pa = new PasswordAuthentication(host // .getUsername(), host.getPassword()); // // URLName url = new URLName(host.getAddress()); // // s.setPasswordAuthentication(url, pa); 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.enjoyxstudy.selenium.autoexec.mail.MailSender.java
/** * @param config/*from w w w .ja v a2 s . com*/ * @throws Exception */ public MailSender(final MailConfiguration config) throws Exception { this.config = config; Properties prop = new Properties(); if (config.isSsl()) { prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); prop.setProperty("mail.smtp.socketFactory.fallback", "false"); prop.setProperty("mail.smtp.socketFactory.port", String.valueOf(config.getPort())); } prop.setProperty("mail.transport.protocol", config.getProtocol()); prop.setProperty("mail.smtp.host", config.getHost()); prop.setProperty("mail.smtp.port", String.valueOf(config.getPort())); log.info("smtp host:" + config.getHost() + " port:" + config.getPort()); prop.setProperty("mail.smtp.connectiontimeout", String.valueOf(config.getConnectionTimeout())); prop.setProperty("mail.smtp.timeout", String.valueOf(config.getReadTimeout())); prop.setProperty("mail.debug", String.valueOf(config.isDebug())); if (config.getUsername() != null && config.getUsername().length() != 0) { prop.setProperty("mail.smtp.auth", "true"); session = Session.getInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getUsername(), config.getPassword()); } }); } else { session = Session.getInstance(prop); } log.info("smtp host:" + config.getHost()); }
From source file:org.mobicents.servlet.restcomm.email.EmailService.java
public EmailService(final Configuration config) { this.observers = new ArrayList<ActorRef>(); configuration = config;/* w w w . j a v a 2 s . com*/ host = configuration.getString("host"); port = configuration.getString("port"); user = configuration.getString("user"); password = configuration.getString("password"); final Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); if (user != null && !user.isEmpty()) { properties.setProperty("mail.smtp.user", user); } if (password != null && !password.isEmpty()) { properties.setProperty("mail.smtp.password", password); } if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.transport.protocol", "smtps"); // properties.setProperty("mail.smtp.ssl.enable", "true"); properties.setProperty("mail.smtp.auth", "true"); session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } }); }
From source file:org.b3log.solo.mail.local.MailSender.java
/** * Create session based on the mail properties. * * @return session session from mail properties *///from w w w. j a v a2s. c om private Session getSession() { final Properties props = new Properties(); props.setProperty("mail.smtp.host", mailProperties.getString("mail.smtp.host")); String auth = "true"; if (mailProperties.containsKey("mail.smtp.auth")) { auth = mailProperties.getString("mail.smtp.auth"); } props.setProperty("mail.smtp.auth", auth); props.setProperty("mail.smtp.port", mailProperties.getString("mail.smtp.port")); String starttls = "true"; if (mailProperties.containsKey("mail.smtp.starttls.enable")) { starttls = mailProperties.getString("mail.smtp.starttls.enable"); } props.put("mail.smtp.starttls.enable", starttls); props.put("mail.debug", mailProperties.getString("mail.debug")); props.put("mail.smtp.socketFactory.class", mailProperties.getString("mail.smtp.socketFactory.class")); props.put("mail.smtp.socketFactory.fallback", mailProperties.getString("mail.smtp.socketFactory.fallback")); props.put("mail.smtp.socketFactory.port", mailProperties.getString("mail.smtp.socketFactory.port")); return Session.getInstance(props, new SMTPAuthenticator()); }