List of usage examples for javax.mail.internet InternetAddress InternetAddress
public InternetAddress(String address, String personal) throws UnsupportedEncodingException
From source file:mitm.common.mail.repository.hibernate.MailRepositoryItemEntity.java
@Override public InternetAddress getSender() throws AddressException { return sender != null ? new InternetAddress(sender, false) : null; }
From source file:mitm.common.mail.repository.hibernate.MailRepositoryItemEntity.java
@Override public InternetAddress getOriginator() throws AddressException { return originator != null ? new InternetAddress(originator, false) : null; }
From source file:com.riq.MailHandlerServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("Inside MailServlet doPost"); // TODO get path information to determine target Department for this email PersistenceManager pm = PMF.get().getPersistenceManager(); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try {/*ww w . ja v a 2 s . com*/ MimeMessage msg = new MimeMessage(session, req.getInputStream()); Address sender = msg.getFrom()[0]; Address replyTo = msg.getReplyTo()[0]; // DEBUG // log.info("Message Class: " + msg.getClass()); // log.info("Message Stream: " + msg.getInputStream()); // log.info("Message RawStream: " + msg.getRawInputStream()); // log.info("Message Flags: " + msg.getFlags()); // log.info("Message Content: " + msg.getContent().toString()); // log.info("Message ContentID: " + msg.getContentID()); // log.info("Message ContentMD: " + msg.getContentMD5()); // log.info("Message ContentType: " + msg.getContentType()); // log.info("Message Description: " + msg.getDescription()); // log.info("Message Disposition: " + msg.getDisposition()); // log.info("Message Encoding: " + msg.getEncoding()); // log.info("Message Filename: " + msg.getFileName()); // log.info("Message Line Count: " + msg.getLineCount()); // log.info("Message ID: " + msg.getMessageID()); // log.info("Message Number: " + msg.getMessageNumber()); // log.info("Message Size: " + msg.getSize()); // log.info("Message Subject: " + msg.getSubject()); // log.info("Message RawInputStream: " + msg.getRawInputStream().toString()); // log.info("Message ReplyTo: " + replyTo); // log.info("Message Sender: " + sender.toString()); // log.info("Request URL TO: " + getServletContext()); String alertMsgString = getText(msg); alertMsgString = alertMsgString.replaceAll("Begin forwarded message:", ""); alertMsgString = alertMsgString.replaceAll("Forwarded message", ""); alertMsgString = alertMsgString.replaceAll("Dispatch@co.morris.nj.us", ""); alertMsgString = alertMsgString.replaceAll("Date:", ""); alertMsgString = alertMsgString.replaceAll(">", ""); alertMsgString = alertMsgString.replaceAll("::", "-"); alertMsgString = alertMsgString.replaceAll("< ", ""); alertMsgString = alertMsgString.replaceAll("----------", ""); alertMsgString = alertMsgString.replaceAll("Subject:", ""); alertMsgString = alertMsgString.replaceAll("To:", ""); alertMsgString = alertMsgString.replaceAll("From:", ""); // Added to grab gmail confirmations // alertMsgString = alertMsgString.substring(50, 300); try { String queryDept = "select from " + Department.class.getName() + // TODO: johnreilly workaround for getting allRecipients... // " where dispatchId == '" + toAddressDigitsOnly + "' " + " where dispatchId == '2599' " + " && fromEmail == '" + sender + "' "; log.info("queryDept: " + queryDept); List<Department> depts = (List<Department>) pm.newQuery(queryDept).execute(); if (depts.size() != 0) { for (Department d : depts) { // need to filter further e.g. last two hours String queryAlert = "select from " + Alert.class.getName() + " where deptId == " + depts.get(0).getid() + " && messageId == '" + msg.getMessageID() + "' "; log.info("queryAlert: " + queryAlert); List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute(); log.info("queryAlert Result Qty: " + alerts.size()); if (alerts.size() == 0) { riqGeocode(alertMsgString); // geocode the address from the Alert Map<String, String> geoResults = riqGeocode(alertMsgString); log.info("lat print: " + geoResults.get("lat")); log.info("lng print: " + geoResults.get("lng")); // create the alert Long deptId = depts.get(0).getid(); Long timeStamp = System.currentTimeMillis(); Alert a = new Alert(deptId, timeStamp, alertMsgString.trim(), sender.toString(), "Active", "", geoResults.get("lat"), geoResults.get("lng"), msg.getMessageID()); pm.makePersistent(a); // query to get id of this alert String queryThisAlert = "select from " + Alert.class.getName() + " where deptId == " + deptId + " " + " && timeStamp == " + timeStamp; log.info("queryThisAlert: " + queryThisAlert); List<Alert> thisAlert = (List<Alert>) pm.newQuery(queryThisAlert).execute(); log.info("queryCurrentAlert Result Qty: " + thisAlert.size()); // create Tracking records for "special" Locations String querySpecialLocs = "select from " + Location.class.getName() + " where special == 'yes' && deptId == " + deptId; log.info("querySpecialLocs: " + querySpecialLocs); List<Location> specialLocs = (List<Location>) pm.newQuery(querySpecialLocs).execute(); log.info("querySpecialLocs qty: " + specialLocs.size()); for (Location specL : specialLocs) { Tracking tSL = new Tracking(deptId, thisAlert.get(0).getid(), specL.getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd "location", specL.getid(), null, "autoAddLocation"); pm.makePersistent(tSL); } // search Dept for Location where distant Members presumed not to be responding are set String queryFarawayLocs = "select from " + Location.class.getName() + " where vru == '2' && deptId == " + deptId; log.info("querySpecialLocs: " + queryFarawayLocs); List<Location> farawayLoc = (List<Location>) pm.newQuery(queryFarawayLocs).execute(); log.info("queryFarawayLocs qty: " + farawayLoc.size()); // create Tracking records for Members presumed not to be responder due to fresh ETA String queryFarAwayResponders = "select from " + Member.class.getName() + " where distGroup == '4' "; log.info("queryFarAwayResponders: " + queryFarAwayResponders); List<Member> farawayMembers = (List<Member>) pm.newQuery(queryFarAwayResponders) .execute(); log.info("queryFarAwayResponders qty: " + farawayMembers.size()); if (farawayMembers.size() != 0) { for (Member far : farawayMembers) { Tracking tMFAR = new Tracking(deptId, thisAlert.get(0).getid(), farawayLoc.get(0).getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd "farawayAddMember", far.getid(), null, responseType); pm.makePersistent(tMFAR); } } // TODO: testing restriction HACKER - remove at launch // send alert email String queryMember = "select from " + Member.class.getName() + " where deptId == " + deptId + " && type == 'Hacker' "; List<Member> members = (List<Member>) pm.newQuery(queryMember).execute(); //TODO Geocode address to insure easy navigation //TODO johnreilly: add street and town fields to Alert msg.setFrom( new InternetAddress("admin@responderiq05.appspotmail.com", "FirstResponder")); msg.setSubject("Alert!"); msg.setText(" Y=" + d.getinboundVRU1() + "&N=" + d.getinboundVRU2() + // "&3=" + d.getinboundVRU3() + "&A=" + thisAlert.get(0).getalertMsgString()); // send message to all dept members who permit tracking (and sending email alerts) for (Member m : members) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.getsmsAddress(), m.getfirstName() + "" + m.getlastName())); log.info("Member: " + m.getsmsAddress() + "|" + m.getlastName()); } } // only process for one department - should only be one department break; } } } catch (MessagingException me) { log.info("Error: Messaging"); } catch (IndexOutOfBoundsException mi) { log.info("Error: Out of Bounds"); } // Do not send alert notification if email is a Google Confirmation // if (! sender.toString().contains("mail-noreply@google.com")) { // Transport.send(msg); // } } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { pm.close(); } }
From source file:io.uengine.mail.MailAsyncService.java
@Async public void sendBySmtp(String subject, String text, String fromUser, String fromName, final String toUser, String telephone, InternetAddress[] toCC) { Session session = setMailProperties(toUser); Map<String, Object> model = new HashMap<>(); model.put("subject", subject); model.put("message", text); model.put("name", fromName); model.put("email", fromUser); model.put("telephone", telephone); String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/contactus.vm", "UTF-8", model);//www . jav a 2 s .co m try { InternetAddress from = new InternetAddress(fromUser, fromName); Message message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser)); message.setSubject(subject); // message.setText(text); 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:fi.hoski.web.forms.RaceEntryServlet.java
/** * Handles the HTTP/*from ww w . java2s . c o m*/ * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String raceFleetKeyStr = request.getParameter("RaceFleetKey"); if (raceFleetKeyStr == null) { throw new ServletException("no RaceFleetKey"); } Key raceFleetKey = KeyFactory.stringToKey(raceFleetKeyStr); Entity raceFleetEntity = datastore.get(raceFleetKey); Key raceSeriesKey = raceFleetKey.getParent(); Entity raceseriesEntity = datastore.get(raceSeriesKey); RaceSeries raceSeries = (RaceSeries) entities.newInstance(raceseriesEntity); RaceFleet raceFleet = (RaceFleet) entities.newInstance(raceFleetEntity); RaceEntry raceEntry = new RaceEntry(raceFleet); raceEntry.populate(request.getParameterMap()); String fn = request.getParameter(RaceEntry.FIRSTNAME); String ln = request.getParameter(RaceEntry.LASTNAME); raceEntry.set(RaceEntry.HELMNAME, fn + " " + ln); String sa = request.getParameter(RaceEntry.STREETADDRESS); String zc = request.getParameter(RaceEntry.ZIPCODE); String ct = request.getParameter(RaceEntry.CITY); String cn = request.getParameter(RaceEntry.COUNTRY); if (cn == null || cn.isEmpty()) { raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct); } else { raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct + ", " + cn); } Day closingDay = (Day) raceSeries.get(RaceSeries.ClosingDate); Number fee = 0.0; if (closingDay != null) { Day now = new Day(); if (closingDay.before(now)) { fee = (Number) raceFleet.get(RaceFleet.Fee2); } else { fee = (Number) raceFleet.get(RaceFleet.Fee); } } Boolean clubDiscount = (Boolean) raceSeries.get(RaceSeries.CLUBDISCOUNT); String clubname = repositoryBundle.getString("Clubname"); if (clubDiscount != null && clubDiscount && clubname.equalsIgnoreCase("" + raceEntry.get(RaceEntry.CLUB))) { fee = new Double(0); } raceEntry.set(RaceEntry.FEE, fee); raceEntry.set(RaceEntry.TIMESTAMP, new Date()); entities.put(raceEntry); String payingInstructions = ""; String payingInstructionsHtml = ""; BankingBarcode bb = races.getBarcode(raceEntry); if (bb != null) { Day dueDay = new Day(bb.getDueDate()); String payingFormat = EntityReferences.encode(msg(Messages.RACEENTRYPAYING), "UTF-8"); String bic = EntityReferences.encode(msg(Messages.RACEBIC), "UTF-8"); payingInstructions = String.format(payingFormat, bb.toString(), // 1 = barcode bb.getAccount().getIBAN(), // 2 = account bb.getReference().toFormattedRFString(), // 3 = ref dueDay, // 4 = due date String.format("%.2f", bb.getTotal()), // 5 = total bic // 6 = bic ); payingInstructionsHtml = String.format(payingFormat.replace("\n", "<br>"), "<span id='barcode'>" + bb.toString() + "</span>", // 1 = barcode "<span id='iban'>" + bb.getAccount().getIBAN() + "</span>", // 2 = account "<span id='rf'>" + bb.getReference().toFormattedRFString() + "</span>", // 3 = ref "<span id='due'>" + dueDay + "</span>", // 4 = due date "<span id='fee'>" + String.format("%.2f", bb.getTotal()) + "</span>", // 5 = total "<span id='bic'>" + bic + "</span>" // 6 = bic ); } URL base = new URL(request.getRequestURL().toString()); URL barcodeUrl = new URL(base, "/races/code128.html?ancestor=" + raceEntry.createKeyString()); String name = (String) raceEntry.get(RaceEntry.HELMNAME); String email = (String) raceEntry.get(RaceEntry.HELMEMAIL); String confirmation = msg(Messages.RACEENTRYCONFIRMATION); String plainMessage = ""; String htmlMessage = "<html><head></head><body>" + EntityReferences.encode(confirmation) + payingInstructionsHtml + raceEntry.getFieldsAsHtmlTable() + "<iframe src=" + barcodeUrl.toString() + "/>" + "</body></html>"; if (email != null) { InternetAddress recipient = new InternetAddress(email, name); String senderStr = msg(Messages.RACEENTRYFROMADDRESS); InternetAddress sender; try { sender = new InternetAddress(senderStr); plainMessage = confirmation + "\n" + payingInstructions + "\n" + raceEntry.getFields(); String subject = msg(Messages.RACEENTRYSUBJECT); mailService.sendMail(sender, subject, plainMessage, htmlMessage, recipient); } catch (Exception ex) { log(senderStr, ex); } } Cookie cookie = null; Cookie[] cookies = null; if (useCookies) { cookies = request.getCookies(); } if (cookies != null) { for (Cookie ck : cookies) { if (COOKIENAME.equals(ck.getName())) { cookie = ck; } } } JSONObject json = null; if (useCookies && cookie != null) { Base64 decoder = new Base64(); String str = new String(decoder.decode(cookie.getValue())); json = new JSONObject(str); } else { json = new JSONObject(); } for (Map.Entry<String, String[]> entry : ((Map<String, String[]>) request.getParameterMap()) .entrySet()) { String property = entry.getKey(); String[] values = entry.getValue(); if (values.length == 1) { json.put(property, values[0]); } } Base64 encoder = new Base64(); String base64 = encoder.encodeAsString(json.toString().getBytes("UTF-8")); if (useCookies) { if (cookie == null) { cookie = new Cookie(COOKIENAME, base64); cookie.setPath("/"); cookie.setMaxAge(400 * 24 * 60 * 60); } else { cookie.setValue(base64); } response.addCookie(cookie); } sendError(response, HttpServletResponse.SC_OK, "<div id=\"" + raceEntry.createKeyString() + "\">Ok</div>"); } catch (JSONException ex) { log(ex.getMessage(), ex); sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "<div id=\"eJSON\">Internal error.</div>"); } catch (EntityNotFoundException ex) { log(ex.getMessage(), ex); sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "<div id=\"eEntityNotFound\">Internal error.</div>"); } catch (NumberFormatException ex) { log(ex.getMessage(), ex); sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eNumberFormat\">Number error.</div>"); } }
From source file:com.liferay.portal.ejb.UserManagerImpl.java
public int notifyNewUsers() throws PortalException, SystemException { String companyId = getUser().getCompanyId(); if (!hasAdministrator(companyId)) { throw new PrincipalException(); }/*from w ww . j a v a 2s . c om*/ UserConfig userConfig = AdminConfigManagerUtil.getUserConfig(companyId); EmailConfig registrationEmail = userConfig.getRegistrationEmail(); if (registrationEmail == null || !registrationEmail.isSend()) { return 0; } // Send email notification Company company = CompanyUtil.findByPrimaryKey(companyId); String adminName = company.getAdminName(); String subject = registrationEmail.getSubject(); String body = registrationEmail.getBody(); List users = UserUtil.findByC_P(companyId, "password"); for (int i = 0; i < users.size(); i++) { User user = (User) users.get(i); user.setPassword(PwdToolkitUtil.generate()); UserUtil.update(user); subject = StringUtil.replace(subject, new String[] { "[$ADMIN_EMAIL_ADDRESS$]", "[$ADMIN_NAME$]", "[$COMPANY_MX$]", "[$COMPANY_NAME$]", "[$PORTAL_URL$]", "[$USER_EMAIL_ADDRESS$]", "[$USER_NAME$]", "[$USER_PASSWORD$]" }, new String[] { company.getEmailAddress(), adminName, company.getMx(), company.getName(), company.getPortalURL(), user.getEmailAddress(), user.getFullName(), user.getPassword() }); body = StringUtil.replace(body, new String[] { "[$ADMIN_EMAIL_ADDRESS$]", "[$ADMIN_NAME$]", "[$COMPANY_MX$]", "[$COMPANY_NAME$]", "[$PORTAL_URL$]", "[$USER_EMAIL_ADDRESS$]", "[$USER_NAME$]", "[$USER_PASSWORD$]" }, new String[] { company.getEmailAddress(), adminName, company.getMx(), company.getName(), company.getPortalURL(), user.getEmailAddress(), user.getFullName(), user.getPassword() }); try { MailManagerUtil.sendEmail(new MailMessage(new InternetAddress(company.getEmailAddress(), adminName), new InternetAddress(user.getEmailAddress(), user.getFullName()), subject, body)); } catch (IOException ioe) { throw new SystemException(ioe); } } return users.size(); }
From source file:com.duroty.application.mail.manager.SendManager.java
/** * DOCUMENT ME!//from w w w .j ava2 s . c o m * * @param hsession DOCUMENT ME! * @param session DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param ideIdint DOCUMENT ME! * @param to DOCUMENT ME! * @param cc DOCUMENT ME! * @param bcc DOCUMENT ME! * @param subject DOCUMENT ME! * @param body DOCUMENT ME! * @param attachments DOCUMENT ME! * @param isHtml DOCUMENT ME! * @param charset DOCUMENT ME! * @param headers DOCUMENT ME! * @param priority DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint, String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml, String charset, InternetHeaders headers, String priority) throws MailException { try { if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } if ((body == null) || body.trim().equals("")) { body = " "; } Email email = null; if (isHtml) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charset); Users user = getUser(hsession, repositoryName); Identity identity = getIdentity(hsession, ideIdint, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null); InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null); InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _to); email.setTo(aux); } if ((_cc != null) && (_cc.length > 0)) { HashSet aux = new HashSet(_cc.length); Collections.addAll(aux, _cc); email.setCc(aux); } if ((_bcc != null) && (_bcc.length > 0)) { HashSet aux = new HashSet(_bcc.length); Collections.addAll(aux, _bcc); email.setBcc(aux); } email.setSubject(subject); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } if ((attachments != null) && (attachments.size() > 0)) { for (int i = 0; i < attachments.size(); i++) { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { MailPartObj obj = (MailPartObj) attachments.get(i); File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); if (email instanceof MultiPartEmail) { ((MultiPartEmail) email).attach(attachment); } } catch (Exception ex) { } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } } if (headers != null) { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) { email.addHeader(xheader.getName(), xheader.getValue()); } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) { email.addHeader(xheader.getName(), xheader.getValue()); } } } if (priority != null) { if (priority.equals("high")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "1"); } else if (priority.equals("low")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "5"); } } if (email instanceof HtmlEmail) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeDraftMessage(getId(), mime, user); } catch (MailException e) { throw e; } catch (Exception e) { throw new MailException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }