List of usage examples for javax.mail Session getInstance
public static Session getInstance(Properties props, Authenticator authenticator)
From source file:ua.aits.sdolyna.controller.MainController.java
@RequestMapping(value = { "/sendmail/", "/sendmail" }, method = RequestMethod.GET) public @ResponseBody String sendMail(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); String email = request.getParameter("email"); String text = request.getParameter("text"); final String username = "office@crc.org.ua"; final String password = "crossroad2000"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication(username, password); }/*from www . ja va2 s .com*/ }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(email)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("sonyachna-dolyna@ukr.net")); message.setSubject("E-mail ? ?:"); message.setText("?: " + name + "\nEmail: " + email + "\n\n" + text); Transport.send(message); return "done"; } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:sendhtml.java
public sendhtml(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;//w w w. ja v a2s. c om String mailer = "sendhtml"; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = 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("-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("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: sendhtml [[-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] [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(); // XXX - could use Session.getTransport() and Transport.connect() // XXX - assume we're using SMTP if (mailhost != null) props.put("mail.smtp.host", mailhost); // 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); collect(in, msg); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off Transport.send(msg); 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) { e.printStackTrace(); } }
From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java
public void sendMail(Mail mail) { LOG.debug("sendEmail() to: " + mail.getRecipient()); try {/*from w w w . j av a2s. co m*/ Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator); session.setDebug(false); MimeMessage msg = new MimeMessage(session); msg.setFrom(m_bag.m_fromAddress); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient())); msg.setSubject(mail.getSubject()); msg.setSentDate(new Date()); Multipart mp = new MimeMultipart(); MimeBodyPart txtmbp = new MimeBodyPart(); txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE); mp.addBodyPart(txtmbp); List<String> attachments = mail.getAttachments(); for (Iterator<String> it = attachments.iterator(); it.hasNext();) { MimeBodyPart mbp = new MimeBodyPart(); String filename = it.next(); FileDataSource fds = new FileDataSource(filename); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeText(fds.getName())); mp.addBodyPart(mbp); } msg.setContent(mp); if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null) && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) { cheat(msg, m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@"))); } Transport.send(msg); LOG.info("Successfully send the mail to " + mail.getRecipient()); } catch (Throwable e) { LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e); LOG.debug("Details:", e); } }
From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java
public void send(EmailModel model) throws EmailException { if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email: " + model); if (model == null) throw new NullPointerException("model"); Properties emailProps;//w w w . j a v a 2 s . c o m Session emailSession; // set the relay host as a property of the email session emailProps = new Properties(); emailProps.setProperty("mail.transport.protocol", "smtp"); emailProps.put("mail.smtp.host", host); emailProps.setProperty("mail.smtp.port", String.valueOf(port)); // set the timeouts emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS)); emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS)); if (LOGGER.isDebugEnabled()) LOGGER.debug("Email properties: " + emailProps); // set up email session emailSession = Session.getInstance(emailProps, null); emailSession.setDebug(false); String from; String displayFrom; String body; String subject; List<EmailAttachment> attachments; if (model.getFrom() == null) throw new NullPointerException("from"); if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc()) && MiscUtils.isEmpty(model.getCc())) throw new IllegalArgumentException("model has no addresses"); from = model.getFrom(); displayFrom = model.getDisplayFrom(); body = model.getBody(); subject = model.getSubject(); attachments = model.getAttachments(); MimeMessage emailMessage; InternetAddress emailAddressFrom; // create an email message from the current session emailMessage = new MimeMessage(emailSession); // set the from try { emailAddressFrom = new InternetAddress(from, displayFrom); emailMessage.setFrom(emailAddressFrom); } catch (Exception e) { throw new IllegalStateException(e); } if (!MiscUtils.isEmpty(model.getTo())) setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO); if (!MiscUtils.isEmpty(model.getCc())) setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC); if (!MiscUtils.isEmpty(model.getBcc())) setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC); try { if (!MiscUtils.isEmpty(subject)) emailMessage.setSubject(subject); Multipart multipart = new MimeMultipart(); if (body != null) { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); //fill message String bodyContentType; // body = Utils.base64Encode(body); bodyContentType = "text/html; charset=UTF-8"; messageBodyPart.setContent(body, bodyContentType); //Content-Transfer-Encoding : base64 // messageBodyPart.addHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(messageBodyPart); } // Part two is attachment if (attachments != null && !attachments.isEmpty()) { try { for (EmailAttachment a : attachments) { MimeBodyPart attachBodyPart = new MimeBodyPart(); // don't base 64 encode DataSource source = new StreamDataSource( new DefaultStreamFactory(a.getInputStream(), false), a.getName(), a.getContentType()); attachBodyPart.setDataHandler(new DataHandler(source)); attachBodyPart.setFileName(a.getName()); attachBodyPart.setHeader("Content-Type", a.getContentType()); attachBodyPart.addHeader("Content-Transfer-Encoding", "base64"); // add the attachment to the message multipart.addBodyPart(attachBodyPart); } } // close all the input streams finally { for (EmailAttachment a : attachments) MiscUtils.closeStream(a.getInputStream()); } } // set the content emailMessage.setContent(multipart); emailMessage.saveChanges(); if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email message: " + emailMessage); Transport.send(emailMessage); if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email complete."); } catch (Exception e) { throw new EmailException(e); } }
From source file:org.webguitoolkit.messagebox.mail.MailChannel.java
/** * /*from w w w. jav a 2s . c om*/ */ @Override public List<IMessage> receive(boolean clear) { List<IMessage> result = new ArrayList<IMessage>(); try { String user = properties.getProperty("pop3.login.user"); String password = properties.getProperty("pop3.login.password"); String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties pop3Props = new Properties(); pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port")); pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port")); URLName url = new URLName("pop3", properties.getProperty("pop3.host"), Integer.valueOf(properties.getProperty("pop3.port")), "", user, password); Session session = Session.getInstance(pop3Props, null); Store store = new POP3SSLStore(session, url); store.connect(); // Open the Folder Folder folder = store.getDefaultFolder(); folder = folder.getFolder("INBOX"); if (folder == null) { throw new RuntimeException("Invalid folder INBOX"); } // try to open read/write and if that fails try read-only try { folder.open(Folder.READ_WRITE); } catch (MessagingException ex) { folder.open(Folder.READ_ONLY); } int count = folder.getMessageCount(); // Message numbers start at 1 for (int i = 1; i <= count; i++) { // Get a message by its sequence number Message m = folder.getMessage(i); Address[] from = m.getFrom(); String type = from[0].getType(); IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m)); result.add(message); // delete message ? if (clear) m.setFlag(Flags.Flag.DELETED, true); } // "true" actually deletes flagged messages from folder folder.close(clear); store.close(); } catch (Exception e) { throw new RuntimeException(e); } return result; }
From source file:org.georchestra.console.mailservice.Email.java
protected void sendMsg(String msg) throws AddressException, MessagingException { if (LOG.isDebugEnabled()) { LOG.debug("body: " + msg); }// w w w . j av a 2s . c o m // Replace {publicUrl} token with the configured public URL msg = msg.replaceAll("\\{publicUrl\\}", this.georConfig.getProperty("publicUrl")); final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", smtpHost); session.getProperties().setProperty("mail.smtp.port", (new Integer(smtpPort)).toString()); final MimeMessage message = new MimeMessage(session); if (isValidEmailAddress(from)) { message.setFrom(new InternetAddress(from)); } boolean validRecipients = false; for (String recipient : recipients) { if (isValidEmailAddress(recipient)) { validRecipients = true; message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } } if (!validRecipients) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(from)); message.setSubject("[ERREUR] Message non dlivr : " + subject, subjectEncoding); } else { message.setSubject(subject, subjectEncoding); } if (msg != null) { /* See http://www.rgagnon.com/javadetails/java-0321.html */ if ("true".equalsIgnoreCase(emailHtml)) { message.setContent(msg, "text/html; charset=" + bodyEncoding); } else { message.setContent(msg, "text/plain; charset=" + bodyEncoding); } LOG.debug(msg); } Transport.send(message); LOG.debug("email has been sent to:\n" + Arrays.toString(recipients)); }
From source file:com.cubusmail.server.mail.imap.IMAPMailbox.java
public void init(String username, String password) { this.username = username; Properties props = new Properties(); props.put("mail.user", username); props.put("mail.imap.partialfetch", this.imapPartialfetch); props.put("mail.imap.fetchsize", this.imapFetchsize); String imapProtocol = this.imapSSL ? "imaps" : "imap"; props.put("mail.store.protocol", imapProtocol); props.put("mail." + imapProtocol + ".port", this.imapPort); props.put("mail." + imapProtocol + ".host", this.imapHost); String smtpProtocol = this.smtpSSL ? "smtps" : "smtp"; props.put("mail.transport.protocol", smtpProtocol); props.put("mail." + smtpProtocol + ".port", this.smtpPort); props.put("mail." + smtpProtocol + ".host", this.smtpHost); // avoid strange ssl exceptions props.put("mail." + smtpProtocol + ".quitwait", "false"); props.put("mail." + smtpProtocol + ".auth", "true"); props.put("mail.mime.decodetext.strict", "true"); props.put("mail.mime.address.strict", "false"); props.put("mail.mime.charset", CubusConstants.DEFAULT_CHARSET); // Security.setProperty( "ssl.SocketFactory.provider", // AllCertificatesSSLSocketFactory.class.getName() ); // props.put( "mail.imap.socketFactory.class", // AllCertificatesSSLSocketFactory.class.getName() ); // props.put( "mail.imap.socketFactory.port", // Configuration.get().imapPort ); // props.put( "mail.imap.socketFactory.fallback", "false" ); // props.put( "mail.smtp.starttls.enable", "true" ); this.mailboxAuthenticator.setUsername(username); this.mailboxAuthenticator.setPassword(password); Session session = Session.getInstance(props, this.mailboxAuthenticator); session.setDebug(false);//www .j av a 2 s . co m this.session = session; }
From source file:mupomat.view.PodrskaLozinka.java
private void posaljiEmail() { final String username = "mupomat@gmail.com"; final String password = "lesnibokysr187"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override/* w w w .j a va 2 s . co m*/ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("mupomat@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(txtEmail.getText().trim())); message.setSubject("MUPomat podrka"); message.setText("Nova lozinka: " + generiranaLozinka + "\nMolimo Vas da nakon prijave promjenite lozinku radi sigurnosti.\nHvala."); Transport.send(message); this.dispose(); JOptionPane.showMessageDialog(rootPane, "Lozinka je uspjeno poslana na Vau e-mail adresu!", "MUPomat: Podrka", JOptionPane.INFORMATION_MESSAGE); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:com.mgmtp.jfunk.core.mail.EmailModule.java
@Provides @TransportSession/* w ww . jav a2 s . co m*/ Session provideTransportSession(final Configuration config) throws GeneralSecurityException { String protocol = checkNotNull(config.get(MAIL_TRANSPORT_PROTOCOL), "Property %s not configured.", MAIL_TRANSPORT_PROTOCOL); Properties sessionProps = new Properties(); sessionProps.putAll(filterKeys(config, contains('.' + protocol + '.'))); sessionProps.setProperty(MAIL_DEBUG, config.get(MAIL_DEBUG, "false")); sessionProps.setProperty(MAIL_TRANSPORT_PROTOCOL, protocol); String user = config.get("mail." + protocol + ".user"); String password = config.get("mail." + protocol + ".password"); if (config.getBoolean("mail.ssl.trust")) { MailSSLSocketFactory socketFactory = new MailSSLSocketFactory(); socketFactory.setTrustAllHosts(true); sessionProps.put("mail." + protocol + ".ssl.socketFactory", socketFactory); } return !isNullOrEmpty(user) && !isNullOrEmpty(password) ? Session.getInstance(sessionProps, new MailAuthenticator(user, password)) : Session.getInstance(sessionProps); }
From source file:com.project.implementation.ReservationImplementation.java
public String makeReservation(GuestDTO guestDTO, Integer no_of_rooms_Int, Date checkin_date, Date checkout_date) {//w w w . j a v a 2s . c o m Integer guestID = 0, guestCount; String room_selected = guestDTO.getRoom_no_selected(); Guest guestObject = new Guest(); try { org.apache.commons.beanutils.BeanUtils.copyProperties(guestObject, guestDTO); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //check email id if exist guestID = guestDAO.checkGuestExist(guestDTO.getGuest_email(), guestDTO.getLicense_no()); System.out.println("guestID: " + guestID); //if email id, license exist if (!(guestID == 0)) { System.out.println("value = "); //update details guestCount = guestDAO.updateUserDetails(guestID, guestDTO.getGuest_name(), guestDTO.getStreet(), guestDTO.getCity(), guestDTO.getState(), guestDTO.getZip()); if (guestCount != 0) guestObject = guestDAO.getGuestRecord(guestID); } else { guestObject = guestDAO.save(guestObject); } String randomDate = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis()); UUID id = UUID.randomUUID(); String token_no = String.valueOf(id); //System.out.println(sensor_id); // String token_no = guestObject.getLicense_no() + guestObject.getGuest_id()+randomDate; java.util.Date todayUtilDate = Calendar.getInstance().getTime();//2015-12-05 java.sql.Date todaySqlDate = new java.sql.Date(todayUtilDate.getTime()); Reservation reservationObject = new Reservation(); // reservationObject.setReservation_id(0); reservationObject.setGuest_id(guestObject.getGuest_id()); reservationObject.setReservation_token(token_no); reservationObject.setReservation_date(todaySqlDate); reservationObject.setReservation_status(ReservationStatus.R); reservationObject = reservationDAO.save(reservationObject); // Integer reservation_id = reservationObject.getReservation_id(); String[] resultStringArray = guestDTO.getRoom_no_selected().split(","); ArrayList<Integer> arrRooms = new ArrayList<Integer>(); for (String str : resultStringArray) { arrRooms.add(Integer.parseInt(str)); CheckinRoomMapping checkinRoomMappingObject = new CheckinRoomMapping(); checkinRoomMappingObject.setReservation(reservationObject); checkinRoomMappingObject.setRoom_no(Integer.parseInt(str)); checkinRoomMappingObject.setCheckin_date(checkin_date); checkinRoomMappingObject.setCheckout_date(checkout_date); checkinRoomMappingObject.setGuest_count(0); checkinRoomMappingObject.setMappingId(0); checkinRoomMappingDAO.save(checkinRoomMappingObject); } //add email code start here final String from = "express.minihotel@gmail.com"; String to = guestObject.getGuest_email(); String body = "Hello " + guestObject.getGuest_name() + ", <br/><br></br>Your reservation has been confirmed.Your reservation ID is <font color='red'><b>" + token_no + "</b></font>.</br>Please bring the Driving License for verification at the time of Check In.</br><br></br>" + "<b>Note:</b>If you want to cancel the reservation, " + "please <a href=\'http://52.53.255.195:8080/CmpE275Team07Fall2015TermProject/v1/cancelReservation?reservation_token=" + token_no + "\'>Click Here</a><br></br>--<i>Express Hotel</i>"; String subject = "Express Hotel Reservation Confirmation <" + token_no + ">"; final String password = "Minihotel@2015"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { MimeMessage email = new MimeMessage(session); email.setFrom(new InternetAddress(from)); email.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to)); email.setSubject(subject); email.setContent(body, "text/html"); Transport.send(email); } catch (MessagingException e) { throw new RuntimeException(e); } //email code end here return token_no; }