List of usage examples for javax.mail.internet MimeMessage setRecipients
public void setRecipients(Message.RecipientType type, String addresses) throws MessagingException
From source file:org.overlord.sramp.governance.services.NotificationResource.java
/** * POST to email a notification about an artifact. * * @param environment//from w w w. j a va 2s . c o m * @param uuid * @throws SrampAtomException */ @POST @Path("email/{group}/{template}/{target}/{uuid}") @Produces("application/xml") public Map<String, ValueEntity> emailNotification(@Context HttpServletRequest request, @PathParam("group") String group, @PathParam("template") String template, @PathParam("target") String target, @PathParam("uuid") String uuid) throws Exception { Map<String, ValueEntity> results = new HashMap<String, ValueEntity>(); try { // 0. run the decoder on the arguments, after replacing * by % (this so parameters can // contain slashes (%2F) group = SlashDecoder.decode(group); template = SlashDecoder.decode(template); target = SlashDecoder.decode(target); uuid = SlashDecoder.decode(uuid); // 1. get the artifact from the repo SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient(); QueryResultSet queryResultSet = client.buildQuery("/s-ramp[@uuid = ?]").parameter(uuid).query(); //$NON-NLS-1$ if (queryResultSet.size() == 0) { results.put(GovernanceConstants.STATUS, new ValueEntity("fail")); //$NON-NLS-1$ results.put(GovernanceConstants.MESSAGE, new ValueEntity("Could not obtain artifact from repository.")); //$NON-NLS-1$ return results; } ArtifactSummary artifactSummary = queryResultSet.iterator().next(); // 2. get the destinations for this group NotificationDestinations destinations = governance.getNotificationDestinations("email").get(group); //$NON-NLS-1$ if (destinations == null) { destinations = new NotificationDestinations(group, governance.getDefaultEmailFromAddress(), group + "@" + governance.getDefaultEmailDomain()); //$NON-NLS-1$ } // 3. send the email notification try { MimeMessage m = new MimeMessage(mailSession); Address from = new InternetAddress(destinations.getFromAddress()); Address[] to = new InternetAddress[destinations.getToAddresses().length]; for (int i = 0; i < destinations.getToAddresses().length; i++) { to[i] = new InternetAddress(destinations.getToAddresses()[i]); } m.setFrom(from); m.setRecipients(Message.RecipientType.TO, to); String subject = "/governance-email-templates/" + template + ".subject.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$ URL subjectUrl = Governance.class.getClassLoader().getResource(subject); if (subjectUrl != null) subject = IOUtils.toString(subjectUrl); subject = subject.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$ subject = subject.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$ subject = subject.replaceAll("\\$\\{target}", target); //$NON-NLS-1$ m.setSubject(subject); m.setSentDate(new java.util.Date()); String content = "/governance-email-templates/" + template + ".body.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$ URL contentUrl = Governance.class.getClassLoader().getResource(content); if (contentUrl != null) content = IOUtils.toString(contentUrl); content = content.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$ content = content.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$ content = content.replaceAll("\\$\\{target}", target); //$NON-NLS-1$ content = content.replaceAll("\\$\\{dtgovurl}", governance.getDTGovUiUrl()); //$NON-NLS-1$ m.setContent(content, "text/plain"); //$NON-NLS-1$ Transport.send(m); } catch (javax.mail.MessagingException e) { logger.error(e.getMessage(), e); } // 4. build the response results.put(GovernanceConstants.STATUS, new ValueEntity("success")); //$NON-NLS-1$ return results; } catch (Exception e) { logger.error(Messages.i18n.format("NotificationResource.EmailError", e.getMessage(), e)); //$NON-NLS-1$ throw new SrampAtomException(e); } }
From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java
private void applyMessageHeaders(final MimeMessage msg) throws Exception { msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); }/*from ww w .j av a2 s. c om*/ if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } }
From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java
private void sendEmail(boolean test, AmazonSimpleEmailServiceClient emailService, String email, List<ApplicationGroup> appGroups) throws IOException, MessagingException { StringBuilder body = new StringBuilder(); body.append(/*from www . ja v a2s. c o m*/ "<html><head><style type=\"text/css\">a:link, a:visited{color:#006DBA;}a:link, a:visited, a:hover {\n" + "text-decoration: none;\n" + "}\n" + "body {\n" + "color: #333;\n" + "}" + "</style></head>"); List<MimeBodyPart> mimeBodyParts = Lists.newArrayList(); int index = 0; String subject = ""; for (ApplicationGroup appGroup : appGroups) { boolean hasData = false; for (String prodName : appGroup.data.keySet()) { if (config.productService.getProductByName(prodName) == null) continue; hasData = appGroup.data.get(prodName) != null && appGroup.data.get(prodName).size() > 0; if (hasData) break; } if (!hasData) continue; try { MimeBodyPart mimeBodyPart = constructEmail(index, appGroup, body); index++; if (mimeBodyPart != null) { mimeBodyParts.add(mimeBodyPart); subject = subject + (subject.length() > 0 ? ", " : "") + appGroup.getDisplayName(); } } catch (Exception e) { logger.error("Error contructing email", e); } } body.append("</html>"); if (mimeBodyParts.size() == 0) return; DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0); subject = String.format("%s Weekly AWS Costs (%s - %s)", subject, formatter.print(end.minusWeeks(1)), formatter.print(end)); String toEmail = test ? testEmail : email; Session session = Session.getInstance(new Properties()); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, toEmail); if (!test && !StringUtils.isEmpty(bccEmail)) { mimeMessage.addRecipients(Message.RecipientType.BCC, bccEmail); } MimeMultipart mimeMultipart = new MimeMultipart(); BodyPart p = new MimeBodyPart(); p.setContent(body.toString(), "text/html"); mimeMultipart.addBodyPart(p); for (MimeBodyPart mimeBodyPart : mimeBodyParts) mimeMultipart.addBodyPart(mimeBodyPart); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mimeMessage.setContent(mimeMultipart); mimeMessage.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); rawEmailRequest.setDestinations(Lists.<String>newArrayList(toEmail)); rawEmailRequest.setSource(fromEmail); logger.info("sending email to " + toEmail + " " + body.toString()); emailService.sendRawEmail(rawEmailRequest); }
From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java
public boolean send() { String cc = null;/* www.j a v a 2 s. c o m*/ String bcc = null; String from = props.getProperty("mail.from.default"); String to = props.getProperty("to"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + "with the subject '" + subject + "' and the body " + body); try { // Get a Session object Session session; if (authenticate) { Authenticator authenticator = new EmailAuthenticator(); session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } // construct the message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (from != null) { msg.setFrom(new InternetAddress(from)); } else { // There should be no way to get here logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } if (body != null) { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(textBodyPart); } // need to create a multi-part message... // create the Multipart and add its parts to it // create and fill the first message part IPentahoStreamSource source = attachment; if (source == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source); // create the second message part MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // attach the file to the message attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(attachmentName); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; // TODO: persist the content set for a while... } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java
private void addRecipients(MimeMessage msg, Set<InternetAddress> recipientList, Message.RecipientType recipientType) throws UnsupportedEncodingException, MessagingException { if (recipientList.isEmpty()) { return;/*from ww w . ja v a 2s . com*/ } final Collection<InternetAddress> recipients = recipientFilter != null ? recipientFilter.apply(recipientList) : recipientList; msg.setRecipients(recipientType, toAddressArray(recipients)); }
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Create basic Message which contains all headers. No body is filled * // w ww . ja v a 2 s .co m * @param session the Session * @param action the action * @return message * @throws AddressException * @throws MessagingException * @throws ActionException */ protected Message createMessage(Session session, A action) throws AddressException, MessagingException { MimeMessage message = new MimeMessage(session); SMTPMessage m = action.getMessage(); message.setFrom(new InternetAddress(m.getFrom())); userPreferences.addContact(m.getTo()); userPreferences.addContact(m.getCc()); userPreferences.addContact(m.getBcc()); message.setRecipients(RecipientType.TO, MessageUtils.getRecipients(m.getTo())); message.setRecipients(RecipientType.CC, MessageUtils.getRecipients(m.getCc())); message.setRecipients(RecipientType.BCC, MessageUtils.getRecipients(m.getBcc())); message.setSubject(MessageUtils.encodeTexts(m.getSubject())); message.saveChanges(); return message; }
From source file:com.project.implementation.ReservationImplementation.java
public ArrayList<HashMap<String, String>> calculateBill(String reservation_token, String user_name, Double discountDouble) {/*from w w w . ja v a 2 s.c om*/ //check if service agent exist List<User> userName = userDAO.verifyUserByUserName(user_name); Integer user_id = userName.get(0).getUser_id(); System.out.println("user_id: " + user_id); String userNameString = userName.get(0).getUser_name().toString(); System.out.println("userNameString: " + userNameString); ArrayList<HashMap<String, String>> billList = new ArrayList<HashMap<String, String>>(); HashMap<String, String> billHash = new HashMap<String, String>(); if (user_name.equals(userNameString)) { //fetch reservation id List<Reservation> reservRecords = reservationDAO.find(reservation_token); Integer reservation_id = reservRecords.get(0).getReservation_id(); System.out.println("reservation_id: " + reservation_id); Integer guest_id = reservRecords.get(0).getGuest_id(); System.out.println("guest_id:: " + guest_id); List<Guest> emailRecord = guestDAO.findGuestEmailId(reservRecords.get(0).getGuest_id()); String guestEmailID = emailRecord.get(0).getGuest_email(); String guestName = emailRecord.get(0).getGuest_name(); System.out.println("emailRecord: " + guestEmailID); System.out.println("guestName: " + guestName); System.out.println(reservRecords.size()); System.out.println(reservRecords.get(0).getReservation_id()); Integer s = reservRecords.get(0).getReservation_id(); System.out.println("integer value: " + s); //Integer reservation_id = reservRecords.get(0).getReservation_id(); //fetch checkin mapping table data ReservationDTO reservDTO = new ReservationDTO(); reservDTO.setReservation_id(reservRecords.get(0).getReservation_id()); List<CheckinRoomMapping> checkinMappingRecords = checkinRoomMappingDAO.findMappingForBilling(reservDTO); Date checkin_date = checkinMappingRecords.get(0).getCheckin_date(); Date checkout_date = checkinMappingRecords.get(0).getCheckout_date(); long daysStay = ((checkout_date.getTime() - checkin_date.getTime()) / MILLISECONDS_IN_DAY) + 1;// System.out.println("daysStay: " + daysStay); String noOfDaysStayed = String.valueOf(daysStay);// System.out.println("noOfDaysStayed: " + noOfDaysStayed); Double totalBill = 0.0; ArrayList<HashMap<String, String>> mailContent = new ArrayList<HashMap<String, String>>(); for (int i = 0; i < checkinMappingRecords.size(); i++) { System.out.println("Room(" + i + ") : " + checkinMappingRecords.get(i).getRoom_no()); Integer room_no = checkinMappingRecords.get(i).getRoom_no(); String roomNoInString = String.valueOf(room_no);// System.out.println("roomNoInString: " + roomNoInString); RoomDTO roomDTO = new RoomDTO(); roomDTO.setRoom_no(room_no); Enum<RoomType> roomType = roomDAO.findRoomType(roomDTO); String type = roomType.toString();// if (type.equalsIgnoreCase("K")) type = "King"; if (type.equalsIgnoreCase("Q")) type = "Queen"; if (type.equalsIgnoreCase("SK")) type = "Smoking - King"; if (type.equalsIgnoreCase("SQ")) type = "Smoking - Queen"; System.out.println("room type: " + type); //Fetch price by room type Double roomPrice = roomPriceDAO.getRoomPrice(roomType);// System.out.println("roomPrice:::" + roomPrice); String roomPriceString = String.valueOf(roomPrice); System.out.println("roomPriceString: " + roomPriceString); Double billPerRoom = roomPrice * daysStay;// String billPerRoomString = String.valueOf(billPerRoom); System.out.println("billPerRoomString:" + billPerRoomString); totalBill = totalBill + billPerRoom; //set hash map HashMap<String, String> mailBody = new HashMap<String, String>(); mailBody.put("Room_Number", roomNoInString); mailBody.put("Room_Type", type); mailBody.put("Room_Price", roomPriceString); mailBody.put("NoOfDays", noOfDaysStayed); mailBody.put("BillPerRoom", billPerRoomString); mailContent.add(mailBody); //end hash map System.out.println("-------"); } System.out.println("totalBill::" + totalBill); String templateForEmailBody = ""; for (HashMap<String, String> h : mailContent) { System.out.println("room_numer" + h.get("Room_Number")); templateForEmailBody = templateForEmailBody + "<tr><td>" + h.get("Room_Number") + "</td><td>" + h.get("Room_Type") + "</td><td>" + h.get("Room_Price") + "</td><td>" + h.get("NoOfDays") + "</td><td>" + h.get("BillPerRoom") + "</td><tr><br>"; } System.out.println("templateForEmailBody" + templateForEmailBody); Integer bill_no = guest_id; String bill_no_String = String.valueOf(bill_no); System.out.println("discount" + discountDouble); //String bill_no_String = String.valueOf(discountDouble); Double totalDiscount = (discountDouble / 100) * totalBill; String totalDiscountString = String.valueOf(totalDiscount); Double amountPayable = totalBill - totalDiscount; String amountPayableString = String.valueOf(amountPayable); //ReservationDTO res = new ReservationDTO(); BillingDTO billingDTO = new BillingDTO(); billingDTO.setBill_no(bill_no); billingDTO.setReservation_id(reservation_id); billingDTO.setUser_id(user_id); billingDTO.setDiscount(totalDiscount); billingDTO.setAmount(amountPayable); Reservation resObj = new Reservation(); resObj.setReservation_id(reservation_id); User userObj = new User(); userObj.setUser_id(user_id); Billing billObject = new Billing(); billObject.setBill_no(bill_no); billObject.setReservation(resObj); billObject.setUser(userObj); billObject.setDiscount(totalDiscount); billObject.setAmount(amountPayable); // try { // org.apache.commons.beanutils.BeanUtils.copyProperties(billObject, billingDTO); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } Integer billID = billingDAO.insertBillData(billObject); System.out.println("Bill id after Insert: " + billID); if (billID != null) { //email final String from = "express.minihotel@gmail.com"; String to = guestEmailID; String body = "Hello " + guestName + ",<br><br>You bill details are as follows:<br>" + "<table border='1' style=\"border-collapse: collapse;\"><tr>" + "<td><b>Room Number</b></td>" + "<td><b>Room Type</b></td>" + "<td><b>Price per day ($)</b></td>" + "<td><b>Duration of Stay (days)</b></td>" + "<td><b>Bill for Room ($)</b></td></tr>" + templateForEmailBody + "</table><br>Net Bill: $" + totalBill + "<br><br>" + "Discount: $" + totalDiscountString + "<br></br>" + "<br/><b>Total Bill Paid($): <font color='red'>" + amountPayable + "</font></b><br></br><br></br>Thank You for choosing Express Hotel.<br/><br/><i>--Express Hotel</i>"; String subject = "Express Hotel - Bill Receipt (Receipt No : " + bill_no_String + ")"; 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 billHash.put("bill_amount", amountPayableString); billHash.put("bill_body", body); billList.add(billHash); //return billList; } } else { //username doesnot exist billHash.put("bill_amount", "User does not exist"); billList.add(billHash); //return billList; } return billList; }
From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java
/** * Create basic Message which contains all headers. No body is filled * * @param session the Session//from www . ja v a 2 s . c o m * @param action the action * @return message * @throws AddressException * @throws MessagingException */ public Message createMessage(Session session, SendMessageAction action) throws AddressException, MessagingException { MimeMessage message = new MimeMessage(session); SmtpMessage m = action.getMessage(); message.setFrom(new InternetAddress(m.getFrom())); userPreferences.addContact(m.getTo()); userPreferences.addContact(m.getCc()); userPreferences.addContact(m.getBcc()); message.setRecipients(RecipientType.TO, MessageUtils.getRecipients(m.getTo())); message.setRecipients(RecipientType.CC, MessageUtils.getRecipients(m.getCc())); message.setRecipients(RecipientType.BCC, MessageUtils.getRecipients(m.getBcc())); message.setSentDate(new Date()); message.addHeader("User-Agent:", "HUPA, The Apache JAMES webmail client."); message.addHeader("X-Originating-IP", getClientIpAddr()); message.setSubject(m.getSubject(), "utf-8"); updateHeaders(message, action); message.saveChanges(); return message; }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Send an email. Also sends it as a gmail if applicable, and does password checking. * @param host host of SMTP server/*from w ww .j a va2 s .c o m*/ * @param uName username of email account * @param pWord password of email account * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email * @param toEMailAddr the email addr of who this is going to * @param subject the Textual subject line of the email * @param bodyText the body text of the email (plain text???) * @param fileAttachment and optional file to be attached to the email * @return true if the msg was sent, false if not */ public static ErrorType sendMsg(final String host, final String uName, final String pWord, final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText, final String mimeType, final String port, final String security, final File fileAttachment) { String userName = uName; String password = pWord; if (StringUtils.isEmpty(toEMailAddr)) { UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR"); return ErrorType.Error; } if (StringUtils.isEmpty(fromEMailAddr)) { UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR"); return ErrorType.Error; } //if (isGmailEmail()) //{ // return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment); //} Boolean fail = false; ArrayList<String> userAndPass = new ArrayList<String>(); boolean isSSL = security.equals("SSL"); String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable", "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback", "mail.imap.auth.plain.disable", }; Properties props = System.getProperties(); for (String key : keys) { props.remove(key); } props.put("mail.smtp.host", host); //$NON-NLS-1$ if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) { props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$ } else { props.remove("mail.smtp.port"); } if (StringUtils.isNotEmpty(security)) { if (security.equals("TLS")) { props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (isSSL) { props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.imap.auth.plain.disable", "true"); } } Session session = null; if (isSSL) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(uName, pWord); } }); } else { session = Session.getInstance(props, null); } session.setDebug(instance.isDebugging); if (instance.isDebugging) { log.debug("Host: " + host); //$NON-NLS-1$ log.debug("UserName: " + userName); //$NON-NLS-1$ log.debug("Password: " + password); //$NON-NLS-1$ log.debug("From: " + fromEMailAddr); //$NON-NLS-1$ log.debug("To: " + toEMailAddr); //$NON-NLS-1$ log.debug("Subject: " + subject); //$NON-NLS-1$ log.debug("Port: " + port); //$NON-NLS-1$ log.debug("Security: " + security); //$NON-NLS-1$ } try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEMailAddr)); if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$ { StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$ InternetAddress[] address = new InternetAddress[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { String toStr = st.nextToken().trim(); address[i++] = new InternetAddress(toStr); } msg.setRecipients(Message.RecipientType.TO, address); } else { try { InternetAddress[] address = { new InternetAddress(toEMailAddr) }; msg.setRecipients(Message.RecipientType.TO, address); } catch (javax.mail.internet.AddressException ex) { UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr); return ErrorType.Error; } } msg.setSubject(subject); //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\""); // create the second message part if (fileAttachment != null) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\""); //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\""); MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileAttachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); } else { // add the Multipart to the message msg.setContent(bodyText, mimeType); } final int TRIES = 1; // set the Date: header msg.setSentDate(new Date()); Exception exception = null; // send the message int cnt = 0; do { cnt++; SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$ try { if (isSSL) { Transport.send(msg); } else { t.connect(host, userName, password); t.sendMessage(msg, msg.getAllRecipients()); } fail = false; } catch (SendFailedException mex) { mex.printStackTrace(); exception = mex; } catch (MessagingException mex) { if (mex.getCause() instanceof UnknownHostException) { instance.lastErrorMsg = null; fail = true; UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host); } else if (mex.getCause() instanceof ConnectException) { instance.lastErrorMsg = null; fail = true; UIRegistry.showLocalizedError( "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port); } else { mex.printStackTrace(); exception = mex; } } catch (Exception mex) { mex.printStackTrace(); exception = mex; } finally { if (t != null) { log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$ t.close(); } } if (exception != null) { fail = true; instance.lastErrorMsg = exception.toString(); //wrong username or password, get new one if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$ { UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName); userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow()); if (userAndPass == null) { //the user is done instance.lastErrorMsg = null; return ErrorType.Cancel; } userName = userAndPass.get(0); password = userAndPass.get(1); } } exception = null; } while (fail && cnt < TRIES); } catch (Exception mex) { //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); mex.printStackTrace(); Exception ex = null; if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } return ErrorType.Error; } if (fail) { return ErrorType.Error; } //else return ErrorType.OK; }
From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java
public String send() { List attachmentList = null;// w ww .j a va 2 s. c o m AttachmentData a = null; try { 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); } Session session; session = Session.getInstance(props); session.setDebug(true); MimeMessage msg = new MimeMessage(session); InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName); msg.setFrom(fromIA); InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) }; msg.setRecipients(Message.RecipientType.TO, toIA); if ("yes".equals(ccMe)) { InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) }; msg.setRecipients(Message.RecipientType.CC, ccIA); } msg.setSubject(subject); EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email"); attachmentList = emailBean.getAttachmentList(); StringBuilder content = new StringBuilder(message); ArrayList fileList = new ArrayList(); ArrayList fileNameList = new ArrayList(); if (attachmentList != null) { if (prefixedPath == null || prefixedPath.equals("")) { log.error("samigo.email.prefixedPath is not set"); return "error"; } Iterator iter = attachmentList.iterator(); while (iter.hasNext()) { a = (AttachmentData) iter.next(); if (a.getIsLink().booleanValue()) { log.debug("send(): url"); content.append("<br/>\n\r"); content.append("<br/>"); // give a new line content.append(a.getFilename()); } else { log.debug("send(): file"); File attachedFile = getAttachedFile(a.getResourceId()); fileList.add(attachedFile); fileNameList.add(a.getFilename()); } } } Multipart multipart = new MimeMultipart(); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content.toString(), "text/html"); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); for (int i = 0; i < fileList.size(); i++) { messageBodyPart = new MimeBodyPart(); FileDataSource source = new FileDataSource((File) fileList.get(i)); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName((String) fileNameList.get(i)); multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); Transport.send(msg); } catch (UnsupportedEncodingException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (MessagingException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (ServerOverloadException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (PermissionException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (IdUnusedException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (TypeException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (IOException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } finally { if (attachmentList != null) { if (prefixedPath != null && !prefixedPath.equals("")) { StringBuilder sbPrefixedPath; Iterator iter = attachmentList.iterator(); while (iter.hasNext()) { sbPrefixedPath = new StringBuilder(prefixedPath); sbPrefixedPath.append("/email_tmp/"); a = (AttachmentData) iter.next(); if (!a.getIsLink().booleanValue()) { deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString()); } } } } } return "send"; }