List of usage examples for javax.mail.internet InternetAddress getPersonal
public String getPersonal()
From source file:mailbox.EmailHandler.java
private static void handleMessage(@Nonnull IMAPMessage msg) { Exception exception = null;/*from w w w .ja va2s .c o m*/ long startTime = System.currentTimeMillis(); User author; try { // Ignore auto-replied emails to avoid suffering from tons of // vacation messages. For more details about auto-replied emails, // see https://tools.ietf.org/html/rfc3834 if (isAutoReplied(msg)) { return; } } catch (MessagingException e) { play.Logger.warn("Failed to determine whether the email is auto-replied or not: " + msg, e); } try { // Ignore the email if there is an email with the same id. It occurs // quite frequently because mail servers send an email twice if the // email has two addresses differ from each other: e.g. // yobi+my/proj@mail.com and yobi+your/proj@mail.com. OriginalEmail sameMessage = OriginalEmail.finder.where().eq("messageId", msg.getMessageID()) .findUnique(); if (sameMessage != null) { // Warn if the older email was handled one hour or more ago. Because it is // quite long time so that possibly the ignored email is actually // new one which should be handled. if (sameMessage.getHandledDate().before(new DateTime().minusHours(1).toDate())) { String warn = String.format( "This email '%s' is ignored because an email with" + " the same id '%s' was already handled at '%s'", msg, sameMessage.messageId, sameMessage.getHandledDate()); play.Logger.warn(warn); } return; } } catch (MessagingException e) { play.Logger.warn("Failed to determine whether the email is duplicated or not: " + msg, e); } InternetAddress[] senderAddresses; try { senderAddresses = (InternetAddress[]) msg.getFrom(); } catch (Exception e) { play.Logger.error("Failed to get senders from an email", e); return; } if (senderAddresses == null || senderAddresses.length == 0) { play.Logger.warn("This email has no sender: " + msg); return; } for (InternetAddress senderAddress : senderAddresses) { List<String> errors = new ArrayList<>(); author = User.findByEmail(senderAddress.getAddress()); if (author.isAnonymous()) { continue; } try { createResources(msg, author, errors); } catch (MailHandlerException e) { exception = e; errors.add(e.getMessage()); } catch (Exception e) { exception = e; String shortDescription; try { shortDescription = IMAPMessageUtil.asString(msg); } catch (MessagingException e1) { shortDescription = msg.toString(); } play.Logger.warn("Failed to process an email: " + shortDescription, e); errors.add("Unexpected error occurs"); } if (errors.size() > 0) { String username = senderAddress.getPersonal(); String emailAddress = senderAddress.getAddress(); String helpMessage = getHelpMessage(Lang.apply(author.getPreferredLanguage()), username, errors); reply(msg, username, emailAddress, helpMessage); } try { log(msg, startTime, exception); } catch (MessagingException e) { play.Logger.warn("Failed to log mail request", e); } try { MailboxService.updateLastSeenUID(msg); } catch (MessagingException e) { play.Logger.warn("Failed to update the lastSeenUID", e); } } }
From source file:com.stimulus.archiva.domain.Email.java
protected String getAddresses(Address[] recipients, DisplayMode displayMode) { if (recipients == null) return ""; StringBuffer result = new StringBuffer(); for (int i = 0; i < recipients.length; i++) { if (recipients[i] instanceof InternetAddress) { InternetAddress address = (InternetAddress) recipients[i]; switch (displayMode) { case ALL: if (address.getPersonal() != null) result.append(address.getPersonal()); result.append(" <"); result.append(DecodingUtil.decodeWord(address.getAddress())); result.append(">"); break; case EMAIL_ONLY: result.append(DecodingUtil.decodeWord(address.getAddress())); break; case NAME_ONLY: if (address.getPersonal() != null) result.append(DecodingUtil.decodeWord(address.getPersonal())); else result.append(DecodingUtil.decodeWord(address.getAddress())); break; }/*from ww w.j a v a2 s. c om*/ } else if (recipients[i] instanceof NewsAddress) { result.append("newsgroup:"); result.append(((NewsAddress) recipients[i]).getNewsgroup()); } else result.append(DecodingUtil.decodeWord(recipients[i].toString())); if (i < recipients.length - 1) result.append(", "); } return result.toString().trim(); }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * @param m/*from w w w .ja v a 2s. c o m*/ * @return * @throws Exception */ private String mail2HTML(Message m) throws Exception { /* * Date & subject */ String date = m.getSentDate().toString(); String subject = m.getSubject(); /* * Body */ String body = getBody(m); /* * From */ String from = ""; Address[] addresses = m.getFrom(); for (Address address : addresses) { InternetAddress internetAddress = (InternetAddress) address; from = internetAddress.getPersonal(); } return HtmlRenderer.mail2HTML(from, date, subject, body); }
From source file:org.xwiki.contrib.mailarchive.utils.internal.MailUtils.java
@Override public IMAUser parseUser(final String user, final boolean isMatchLdap) { logger.debug("parseUser {}, {}", user, isMatchLdap); MAUser maUser = new MAUser(); maUser.setOriginalAddress(user);//from w ww . ja v a2s . c om if (StringUtils.isBlank(user)) { return maUser; } String address = null; String personal = null; // Do our best to extract an address and a personal try { InternetAddress ia = null; InternetAddress[] result = InternetAddress.parse(user, true); if (result != null && result.length > 0) { ia = result[0]; if (!StringUtils.isBlank(ia.getAddress())) { address = ia.getAddress(); } if (!StringUtils.isBlank(ia.getPersonal())) { personal = ia.getPersonal(); } } } catch (AddressException e) { logger.info("Email Address does not follow standards : " + user); } if (StringUtils.isBlank(address)) { String[] substrs = StringUtils.substringsBetween(user, "<", ">"); if (substrs != null && substrs.length > 0) { address = substrs[0]; } else { // nothing matches, we suppose recipient only contains email address address = user; } } if (StringUtils.isBlank(personal)) { if (user.contains("<")) { personal = StringUtils.substringBeforeLast(user, "<"); if (StringUtils.isBlank(personal)) { personal = StringUtils.substringBefore(address, "@"); } } } maUser.setAddress(address); maUser.setDisplayName(personal); // Now to match a wiki profile logger.debug("parseUser extracted email {}", address); String parsedUser = null; if (!StringUtils.isBlank(address)) { // to match "-external" emails and old mails with '@gemplus.com'... String pattern = address.toLowerCase(); pattern = pattern.replace("-external", "").replaceAll("^(.*)@.*[.]com$", "$1%@%.com"); logger.debug("parseUser pattern applied {}", pattern); // Try to find a wiki profile with this email as parameter. // TBD : do this in the loading phase, and only try to search db if it was not found ? String xwql = "select doc.fullName from Document doc, doc.object(XWiki.XWikiUsers) as user where LOWER(user.email) like :pattern"; List<String> profiles = null; try { profiles = queryManager.createQuery(xwql, Query.XWQL).bindValue("pattern", pattern).execute(); } catch (QueryException e) { logger.warn("parseUser Query threw exception", e); profiles = null; } if (profiles == null || profiles.size() == 0) { logger.debug("parseUser found no wiki profile from db"); return maUser; } else { if (isMatchLdap) { logger.debug("parseUser Checking for LDAP authenticated profile(s) ..."); // If there exists one, we prefer the user that's been authenticated through LDAP for (String usr : profiles) { if (bridge.exists(usr, "XWiki.LDAPProfileClass")) { parsedUser = usr; logger.debug("parseUser Found LDAP authenticated profile {}", parsedUser); } } if (parsedUser != null) { maUser.setWikiProfile(parsedUser); logger.debug("parseUser return {}", maUser); return maUser; } } } // If none has authenticated from LDAP, we return the first user found maUser.setWikiProfile(profiles.get(0)); logger.debug("parseUser return {}", maUser); return maUser; } else { logger.debug("parseUser No email found to match"); return maUser; } }
From source file:edu.stanford.muse.webapp.JSPHelper.java
public static Pair<String, String> getNameAndURL(InternetAddress a, AddressBook addressBook) { String s = a.getAddress();/*from w w w . j a v a2 s. c o m*/ if (s == null) s = a.getPersonal(); if (s == null) return new Pair<String, String>("", ""); // TODO (maybe after archive data structures re-org): below should pass archive ID to browse page if (addressBook == null) { return new Pair<String, String>(s, "browse?person=" + s); } else { Contact contact = addressBook.lookupByEmail(a.getAddress()); return new Pair<String, String>(s, "browse?contact=" + addressBook.getContactId(contact)); } }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * Retrieve mail messages in a JSON representation * //from ww w . ja va 2s .c om * @return */ public JSONArray getJMessages() { JSONArray jMessages = new JSONArray(); if (store == null) return jMessages; try { /* * Connect to IMAP store */ store.connect(); /* * Retrieve & open INBOX folder */ Folder folder = store.getFolder(ImapConstants.INBOX); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { Message m = messages[i]; JSONObject jMessage = new JSONObject(); jMessage.put(ImapConstants.J_KEY, ""); // introduced to be compatible with posted emails jMessage.put(ImapConstants.J_ID, i); // message identifier to retrieve from external server jMessage.put(ImapConstants.J_SUBJECT, m.getSubject()); jMessage.put(ImapConstants.J_DATE, m.getSentDate()); String from = ""; Address[] addresses = m.getFrom(); for (Address address : addresses) { InternetAddress internetAddress = (InternetAddress) address; from = internetAddress.getPersonal(); } jMessage.put(ImapConstants.J_FROM, from); FileUtil attachment = getAttachment(m); if (attachment == null) { jMessage.put(ImapConstants.J_ATTACHMENT, false); } else { jMessage.put(ImapConstants.J_ATTACHMENT, true); } jMessages.put(jMessages.length(), jMessage); } folder.close(false); store.close(); } catch (Exception e) { e.printStackTrace(); } finally { } return jMessages; }
From source file:org.silverpeas.core.importexport.control.RepositoriesTypeManager.java
private void processMailContent(PublicationDetail pubDetail, File file, ImportReportManager reportManager, UnitReport unitReport, GEDImportExport gedIE, boolean isVersioningUsed) throws ImportExportException { String componentId = gedIE.getCurrentComponentId(); UserDetail userDetail = gedIE.getCurrentUserDetail(); MailExtractor extractor = null;/*from w w w . j av a2 s . c om*/ Mail mail = null; try { extractor = Extractor.getExtractor(file); mail = extractor.getMail(); } catch (Exception e) { SilverLogger.getLogger(this).error("Cannot extract mail data", e); } if (mail != null) { // save mail data into dedicated form String content = mail.getBody(); PublicationContentType pubContent = new PublicationContentType(); XMLModelContentType modelContent = new XMLModelContentType("mail"); pubContent.setXMLModelContentType(modelContent); List<XMLField> fields = new ArrayList<>(); modelContent.setFields(fields); XMLField subject = new XMLField("subject", mail.getSubject()); fields.add(subject); XMLField body = new XMLField("body", ESCAPE_ISO8859_1.translate(content)); fields.add(body); XMLField date = new XMLField("date", DateUtil.getOutputDateAndHour(mail.getDate(), "fr")); fields.add(date); InternetAddress address = mail.getFrom(); String from = ""; if (StringUtil.isDefined(address.getPersonal())) { from += address.getPersonal() + " - "; } from += "<a href=\"mailto:" + address.getAddress() + "\">" + address.getAddress() + "</a>"; XMLField fieldFROM = new XMLField("from", from); fields.add(fieldFROM); Address[] recipients = mail.getAllRecipients(); StringBuilder to = new StringBuilder(); for (Address recipient : recipients) { InternetAddress ia = (InternetAddress) recipient; if (StringUtil.isDefined(ia.getPersonal())) { to.append(ia.getPersonal()).append(" - "); } to.append("<a href=\"mailto:").append(ia.getAddress()).append("\">").append(ia.getAddress()) .append("</a></br>"); } XMLField fieldTO = new XMLField("to", to.toString()); fields.add(fieldTO); // save form gedIE.createPublicationContent(reportManager, unitReport, Integer.parseInt(pubDetail.getPK().getId()), pubContent, userDetail.getId(), null); try { // extract each file from mail... List<AttachmentDetail> documents = extractAttachmentsFromMail(componentId, userDetail, extractor); // ... and save them saveAttachments(componentId, pubDetail, documents, userDetail, gedIE, isVersioningUsed); } catch (Exception e) { SilverLogger.getLogger(this).error(e.getMessage(), e); } } }
From source file:edu.stanford.muse.webapp.JSPHelper.java
public static JSONArray formatAddressesAsJSON(Address addrs[]) throws JSONException { JSONArray result = new JSONArray(); if (addrs == null) return result; int index = 0; for (int i = 0; i < addrs.length; i++) { Address a = addrs[i];// w w w. j ava 2 s . c om if (a instanceof InternetAddress) { InternetAddress ia = (InternetAddress) a; JSONObject o = new JSONObject(); o.put("email", Util.maskEmailDomain(ia.getAddress())); o.put("name", ia.getPersonal()); result.put(index++, o); } } return result; }
From source file:immf.AppNotifications.java
public void run() { boolean authOk = false; if (this.credentials.isEmpty()) { if (!this.auth()) { log.warn(// w w w . j av a 2 s . c o m "???????????"); return; } authOk = true; log.info("credentials??push???"); } else { log.info("push???"); } if (dnsCache) { log.info( "DNS??(SSL????????????)"); } int c = 0; while (true) { try { Thread.sleep(ReconnectInterval); } catch (Exception e) { } // ?????5 if (this.sendMailQueue.size() > 0 && c++ > ReconnectCount) { log.info("push"); } else if (this.recieveMailQueue.size() > newmails) { log.warn(""); } else if (newmails == 0) { continue; } else if (this.recieveMailQueue.size() < newmails) { // ??????? if (c++ > 100) { log.warn("?"); newmails = this.recieveMailQueue.size(); } continue; } c = 0; synchronized (this.recieveMailQueue) { for (int i = this.recieveMailQueue.size(); i > 0; i--) { this.sendMailQueue.add(this.recieveMailQueue.remove()); } newmails = 0; } // push int count = this.sendMailQueue.size(); ImodeMail mail = this.sendMailQueue.peek(); String pushMessage = this.message; String pushCommand = ""; if (!this.pushFromInfo) { pushMessage += "(" + Integer.toString(count) + ")"; } String delimiter = ""; if (!pushMessage.isEmpty()) { delimiter = "\n"; } if (mail != null && this.pushSubjectInfo) { String subject = mail.getSubject(); if (subject.isEmpty()) { subject = "(????)"; } pushMessage += delimiter + subject; delimiter = " "; } if (mail != null && this.pushFromInfo) { InternetAddress fromAddr = mail.getFromAddr(); String from = fromAddr.getPersonal(); if (from == null || from.isEmpty()) { from = fromAddr.getAddress(); } if (count == 1) { pushMessage += delimiter + "(" + from + ")"; } else { pushMessage += delimiter + "(" + from + "," + Integer.toString(count - 1) + ")"; } } if (mail != null && this.pushReplyButton) { // (%20)??+??????? InternetAddress fromAddr = mail.getFromAddr(); pushCommand = "mailto:" + fromAddr.getAddress(); for (InternetAddress to : mail.getToAddrList()) { pushCommand += "%2C" + to.getAddress(); } String ccList = ""; for (InternetAddress cc : mail.getCcAddrList()) { if (ccList.isEmpty()) { ccList = "?cc=" + cc.getAddress(); } else { ccList += "%2C" + cc.getAddress(); } } if (!ccList.isEmpty()) { pushCommand += ccList; //pushCommand += "&subject="; //}else{ //pushCommand += "?subject="; } /* * XXX * Apple URL Scheme Reference?? RFC2368 ????????? * 8bit?? subject ???? RFC2047 ?????? * ??????8bit??? Push ??? * Push ???????? */ } try { log.info("push:" + pushMessage.replace("\n", "/")); if (this.pushReplyButton) { this.send(pushMessage, pushCommand); } else { this.send(pushMessage); } authOk = true; this.sendMailQueue.clear(); } catch (SocketException se) { // log.warn("?push????", se); } catch (ClientProtocolException cpe) { // log.warn("?push????", cpe); } catch (UnknownHostException uhe) { // DNS log.warn("DNS?push????", uhe); } catch (SSLException ssle) { // SSL log.warn("SSL?push????", ssle); } catch (MyHttpException mhe) { // log.warn("??push????", mhe); } catch (Exception e) { log.warn("push???", e); if (authOk) { continue; } // ???????????????? this.credentials = ""; // status.ini???credentials??????????? if (this.auth()) { authOk = true; log.info("credentials???"); try { log.info("push:" + pushMessage.replace("\n", "/")); if (this.pushReplyButton) { this.send(pushMessage, pushCommand); } else { this.send(pushMessage); } this.sendMailQueue.clear(); } catch (Exception ex) { log.warn("pushpush????", e); this.setCredentials(""); this.sendMailQueue.clear(); return; } } else { log.warn("??push????"); this.setCredentials(""); this.sendMailQueue.clear(); return; } } } }
From source file:org.itracker.services.implementations.NotificationServiceImpl.java
/** * Send notifications to mapped addresses by locale. */// w w w . j a va 2s. c o m private void handleNotification(Issue issue, Type type, Map<InternetAddress, Locale> recipientsLocales, final String url, Integer notModifiedSince) { Set<InternetAddress> recipients; Map<Locale, Set<InternetAddress>> localeRecipients = new Hashtable<>(); List<Component> components = issue.getComponents(); List<IssueActivity> activity = getIssueService().getIssueActivity(issue.getId(), false); IssueHistory history; history = getIssueService().getLastIssueHistory(issue.getId()); StringBuilder recipientsString = new StringBuilder(); if (logger.isDebugEnabled() && null != history) { logger.debug("handleIssueNotification: got most recent history: " + history + " (" + history.getDescription() + ")"); } for (InternetAddress internetAddress : recipientsLocales.keySet()) { recipientsString.append("\n "); recipientsString.append(internetAddress.getPersonal()); if (localeRecipients.keySet().contains(recipientsLocales.get(internetAddress))) { localeRecipients.get(recipientsLocales.get(internetAddress)).add(internetAddress); } else { Set<InternetAddress> addresses = new HashSet<>(); addresses.add(internetAddress); localeRecipients.put(recipientsLocales.get(internetAddress), addresses); } } Iterator<Locale> localesIt = localeRecipients.keySet().iterator(); try { while (localesIt.hasNext()) { Locale currentLocale = localesIt.next(); recipients = localeRecipients.get(currentLocale); if (recipients.size() > 0) { String subject; if (type == Type.CREATED) { subject = ITrackerResources.getString("itracker.email.issue.subject.created", currentLocale, new Object[] { issue.getId(), issue.getProject().getName() }); } else if (type == Type.ASSIGNED) { subject = ITrackerResources.getString("itracker.email.issue.subject.assigned", currentLocale, new Object[] { issue.getId(), issue.getProject().getName() }); } else if (type == Type.CLOSED) { subject = ITrackerResources.getString("itracker.email.issue.subject.closed", currentLocale, new Object[] { issue.getId(), issue.getProject().getName() }); } else if (type == Type.ISSUE_REMINDER) { subject = ITrackerResources.getString("itracker.email.issue.subject.reminder", currentLocale, new Object[] { issue.getId(), issue.getProject().getName(), notModifiedSince }); } else { subject = ITrackerResources.getString("itracker.email.issue.subject.updated", currentLocale, new Object[] { issue.getId(), issue.getProject().getName() }); } String activityString; String componentString = ""; StringBuilder sb = new StringBuilder(); if (activity.size() == 0) { sb.append("-"); } else { for (IssueActivity anActivity : activity) { sb.append("\n ").append( IssueUtilities.getActivityName(anActivity.getActivityType(), currentLocale)) .append(": ").append(anActivity.getDescription()); } } sb.append("\n"); activityString = sb.toString(); for (int i = 0; i < components.size(); i++) { componentString += (i != 0 ? ", " : "") + components.get(i).getName(); } final String owner = IssueUtilities.getOwnerName(issue.getOwner(), currentLocale); final User hUser = null == history ? null : history.getUser(); final String historyUser = (null != hUser) ? hUser.getFullName() : ITrackerResources.getString("itracker.web.generic.notapplicable", currentLocale); final String historyText = (history == null ? "-" : HTMLUtilities.removeMarkup(history.getDescription())); final String status = IssueUtilities.getStatusName(issue.getStatus(), currentLocale); final String msgText; if (type == Type.ISSUE_REMINDER) { msgText = ITrackerResources.getString("itracker.email.issue.body.reminder", currentLocale, new Object[] { IssueUtilities.getIssueURL(issue, url).toExternalForm(), issue.getProject().getName(), issue.getDescription(), IssueUtilities.getStatusName(issue.getStatus(), currentLocale), IssueUtilities.getSeverityName(issue.getSeverity(), currentLocale), owner, componentString, historyUser, historyText, notModifiedSince, activityString }); } else { String resolution = (issue.getResolution() == null ? "" : issue.getResolution()); if (!resolution.equals("") && ProjectUtilities.hasOption( ProjectUtilities.OPTION_PREDEFINED_RESOLUTIONS, issue.getProject().getOptions())) { resolution = IssueUtilities.getResolutionName(resolution, currentLocale); } msgText = ITrackerResources.getString( "itracker.email.issue.body." + (type == Type.CREATED ? "created" : "standard"), currentLocale, new Object[] { url + "/module-projects/view_issue.do?id=" + issue.getId(), issue.getProject().getName(), issue.getDescription(), status, resolution, IssueUtilities.getSeverityName(issue.getSeverity(), currentLocale), owner, componentString, historyUser, historyText, activityString, recipientsString }); } if (logger.isInfoEnabled()) { logger.info("handleNotification: sending notification for " + issue + " (" + type + ") to " + currentLocale + "-users (" + recipients + ")"); } for (InternetAddress iadr : recipients) { emailService.sendEmail(iadr, subject, msgText); } if (logger.isDebugEnabled()) { logger.debug("handleNotification: sent notification for " + issue + ": " + subject + "\n " + msgText); } } updateIssueActivityNotification(issue, true); if (logger.isDebugEnabled()) { logger.debug("handleNotification: sent notification for locales " + localeRecipients.keySet() + " recipients: " + localeRecipients.values()); } } } catch (RuntimeException e) { logger.error("handleNotification: failed to notify: " + issue + " (locales: " + localeRecipients.keySet() + ")", e); } catch (MalformedURLException e) { logger.error("handleNotification: URL was not well-formed", e); } }