List of usage examples for javax.mail Transport send
public static void send(Message msg) throws MessagingException
From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java
@Override public void sendInvite(final String subject, final String description, final Participant from, final List<Participant> attendees, final Date startDate, final Date endDate, final String location) throws Exception { this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port")); this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); this.properties.put("mail.smtp.socketFactory.fallback", "false"); validate();// w w w . j a va 2 s . c om LOG.info("Sending meeting invite"); LOG.debug("Mail Properties :: " + this.properties); Session session; if (password != null) { session = Session.getInstance(this.properties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { session = Session.getInstance(this.properties); } ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location); cal.init(); StringBuffer sb = new StringBuffer(); sb.append(from.getEmail()); for (Participant bean : attendees) { if (sb.length() > 0) { sb.append(","); } sb.append(bean.getEmail()); } MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from.getEmail())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString())); message.setSubject(subject); Multipart multipart = new MimeMultipart(); MimeBodyPart iCal = new MimeBodyPart(); iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()), "text/calendar;method=REQUEST;charset=\"UTF-8\""))); LOG.debug("Calender Request :: \n" + cal.toString()); multipart.addBodyPart(iCal); message.setContent(multipart); Transport.send(message); }
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 w w w . j av a 2 s .c o m*/ }); 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.j a v a 2s . c o m*/ 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:org.smartloli.kafka.eagle.api.email.MailServiceImpl.java
/** Send mail in HTML format */ private boolean sendHtmlMail(MailSenderInfo mailInfo) { boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable"); if (enableMailAlert) { SaAuthenticatorInfo authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword()); }//from w w w . j av a 2s . c o m Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { Message mailMessage = new MimeMessage(sendMailSession); Address from = new InternetAddress(mailInfo.getFromAddress()); mailMessage.setFrom(from); Address[] to = new Address[mailInfo.getToAddress().split(",").length]; int i = 0; for (String e : mailInfo.getToAddress().split(",")) to[i++] = new InternetAddress(e); mailMessage.setRecipients(Message.RecipientType.TO, to); mailMessage.setSubject(mailInfo.getSubject()); mailMessage.setSentDate(new Date()); Multipart mainPart = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8"); mainPart.addBodyPart(html); if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) { for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) { MimeBodyPart mbp = new MimeBodyPart(); File file = new File(entry.getValue()); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); try { mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null)); } catch (Exception e) { e.printStackTrace(); } mbp.setContentID(entry.getKey()); mbp.setHeader("Content-ID", "<image>"); mainPart.addBodyPart(mbp); } } List<File> list = mailInfo.getFileList(); if (list != null && list.size() > 0) { for (File f : list) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(f.getAbsolutePath()); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(f.getName()); mainPart.addBodyPart(mbp); } list.clear(); } mailMessage.setContent(mainPart); // mailMessage.saveChanges(); Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } } return false; }
From source file:org.unitime.commons.JavaMailWrapper.java
@Override public void send() throws MessagingException, UnsupportedEncodingException { long t0 = System.currentTimeMillis(); try {// ww w. j a va2 s . c o m if (iMail.getFrom() == null || iMail.getFrom().length == 0) setFrom(ApplicationProperty.EmailSenderAddress.value(), ApplicationProperty.EmailSenderName.value()); if (iMail.getReplyTo() == null || iMail.getReplyTo().length == 0) setReplyTo(ApplicationProperty.EmailReplyToAddress.value(), ApplicationProperty.EmailReplyToName.value()); iMail.setSentDate(new Date()); iMail.setContent(iBody); iMail.saveChanges(); Transport.send(iMail); } finally { long t = System.currentTimeMillis() - t0; if (t > 30000) sLog.warn("It took " + new DecimalFormat("0.00").format(t / 1000.0) + " seconds to send an email."); else if (t > 5000) sLog.info("It took " + new DecimalFormat("0.00").format(t / 1000.0) + " seconds to send an email."); } }
From source file:org.nuxeo.ecm.platform.ec.notification.email.EmailHelper.java
protected void sendmail0(Map<String, Object> mail) throws MessagingException, IOException, TemplateException, LoginException, RenderingException { Session session = getSession();/* www .j a v a 2 s . com*/ if (javaMailNotAvailable || session == null) { log.warn("Not sending email since JavaMail is not configured"); return; } // Construct a MimeMessage MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); Object to = mail.get("mail.to"); if (!(to instanceof String)) { log.error("Invalid email recipient: " + to); return; } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) to, false)); RenderingService rs = Framework.getService(RenderingService.class); DocumentRenderingContext context = new DocumentRenderingContext(); context.remove("doc"); context.putAll(mail); context.setDocument((DocumentModel) mail.get("document")); context.put("Runtime", Framework.getRuntime()); String customSubjectTemplate = (String) mail.get(NotificationConstants.SUBJECT_TEMPLATE_KEY); if (customSubjectTemplate == null) { String subjTemplate = (String) mail.get(NotificationConstants.SUBJECT_KEY); Template templ = new Template("name", new StringReader(subjTemplate), stringCfg); Writer out = new StringWriter(); templ.process(mail, out); out.flush(); msg.setSubject(out.toString(), "UTF-8"); } else { rs.registerEngine(new NotificationsRenderingEngine(customSubjectTemplate)); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String subjectMail = "<HTML><P>No parsing Succeded !!!</P></HTML>"; for (RenderingResult result : results) { subjectMail = (String) result.getOutcome(); } subjectMail = NotificationServiceHelper.getNotificationService().getEMailSubjectPrefix() + subjectMail; msg.setSubject(subjectMail, "UTF-8"); lc.logout(); } msg.setSentDate(new Date()); rs.registerEngine(new NotificationsRenderingEngine((String) mail.get(NotificationConstants.TEMPLATE_KEY))); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String bodyMail = "<HTML><P>No parsing Succedeed !!!</P></HTML>"; for (RenderingResult result : results) { bodyMail = (String) result.getOutcome(); } lc.logout(); rs.unregisterEngine("ftl"); msg.setContent(bodyMail, "text/html; charset=utf-8"); // Send the message. Transport.send(msg); }
From source file:org.apache.axis2.transport.mail.EMailSender.java
public void send() throws AxisFault { try {//from ww w.jav a 2s . c om Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return passwordAuthentication; } }); MimeMessage msg = new MimeMessage(session); // Set date - required by rfc2822 msg.setSentDate(new java.util.Date()); // Set from - required by rfc2822 String from = properties.getProperty("mail.smtp.from"); if (from != null) { msg.setFrom(new InternetAddress(from)); } EndpointReference epr = null; MailToInfo mailToInfo; if (messageContext.getTo() != null && !messageContext.getTo().hasAnonymousAddress()) { epr = messageContext.getTo(); } if (epr != null) { if (!epr.hasNoneAddress()) { mailToInfo = new MailToInfo(epr); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress())); } else { if (from != null) { mailToInfo = new MailToInfo(from); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress())); } else { String error = EMailSender.class.getName() + "Couldn't countinue due to" + " FROM addressing is NULL"; log.error(error); throw new AxisFault(error); } } } else { // replyto : from : or reply-path; if (from != null) { mailToInfo = new MailToInfo(from); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress())); } else { String error = EMailSender.class.getName() + "Couldn't countinue due to" + " FROM addressing is NULL and EPR is NULL"; log.error(error); throw new AxisFault(error); } } msg.setSubject("__ Axis2/Java Mail Message __"); if (mailToInfo.isxServicePath()) { msg.setHeader(Constants.X_SERVICE_PATH, "\"" + mailToInfo.getContentDescription() + "\""); } if (inReplyTo != null) { msg.setHeader(Constants.IN_REPLY_TO, inReplyTo); } createMailMimeMessage(msg, mailToInfo, format); Transport.send(msg); log.info("Message being send. [Action = ]" + messageContext.getOptions().getAction()); sendReceive(messageContext, msg.getMessageID()); } catch (AddressException e) { throw new AxisFault(e.getMessage(), e); } catch (MessagingException e) { throw new AxisFault(e.getMessage(), 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. jav a2 s . com*/ 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:io.uengine.mail.MailAsyncService.java
@Async public void trialCreated(String subject, String fromUser, String fromName, String toUser, InternetAddress[] toCC) {//from w ww.j ava 2s .c om Session session = setMailProperties(toUser); Map model = new HashMap(); model.put("link", "http://www.uengine.io/my/license"); String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/trial-created.vm", "UTF-8", model); try { InternetAddress from = new InternetAddress(fromUser, fromName); MimeMessage message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser)); message.setSubject(subject); message.setContent(body, "text/html; charset=utf-8"); if (toCC != null && toCC.length > 0) message.setRecipients(Message.RecipientType.CC, toCC); Transport.send(message); logger.info("{} ? ?? .", toUser); } catch (Exception e) { throw new ServiceException("?? .", e); } }
From source file:com.project.implementation.ReservationImplementation.java
public String makeReservation(GuestDTO guestDTO, Integer no_of_rooms_Int, Date checkin_date, Date checkout_date) {/*from w w w . ja v a 2 s. 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; }