List of usage examples for javax.mail.internet InternetAddress getAddress
public String getAddress()
From source file:jp.mamesoft.mailsocketchat.Mail.java
public void run() { while (true) { try {/*from w w w.ja va 2s .c om*/ System.out.println("????"); Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); // session.setDebug(true); // Get a Store object Store store = session.getStore("imaps"); // Connect store.connect("imap.gmail.com", 993, Mailsocketchat.mail_user, Mailsocketchat.mail_pass); System.out.println("??????"); // Open a Folder Folder folder = store.getFolder("INBOX"); if (folder == null || !folder.exists()) { System.out.println("IMAP??????"); System.exit(1); } folder.open(Folder.READ_WRITE); // Add messageCountListener to listen for new messages folder.addMessageCountListener(new MessageCountAdapter() { public void messagesAdded(MessageCountEvent ev) { Message[] msgs = ev.getMessages(); // Just dump out the new messages for (int i = 0; i < msgs.length; i++) { try { System.out.println("?????"); InternetAddress addrfrom = (InternetAddress) msgs[i].getFrom()[0]; String subject = msgs[i].getSubject(); if (subject == null) { subject = ""; } Pattern hashtag_p = Pattern.compile("#(.+)"); Matcher hashtag_m = hashtag_p.matcher(subject); if (subject.equals("#")) { hashtag = null; } else if (hashtag_m.find()) { hashtag = hashtag_m.group(1); } String comment = msgs[i].getContent().toString().replaceAll("\r\n", " "); comment = comment.replaceAll("\n", " "); comment = comment.replaceAll("\r", " "); JSONObject data = new JSONObject(); data.put("comment", comment); if (hashtag != null) { data.put("channel", hashtag); } if (!comment.equals("") && !comment.equals(" ") && !comment.equals(" ")) { Mailsocketchat.socket.emit("say", data); System.out.println("????"); } // if (subject.equals("push") || subject.equals("Push") || subject.equals("")) { Send(addrfrom.getAddress(), 2); Mailsocketchat.push = true; Mailsocketchat.repeat = false; Mailsocketchat.address = addrfrom.getAddress(); repeatthread.cancel(); repeatthread = null; System.out.println("?????"); } else if (subject.equals("fetch") || subject.equals("Fetch") || subject.equals("?")) { Send(addrfrom.getAddress(), 3); Mailsocketchat.push = false; Mailsocketchat.repeat = false; repeatthread.cancel(); repeatthread = null; System.out.println("??????"); } else if (subject.equals("repeat") || subject.equals("Repeat") || subject.equals("")) { Send(addrfrom.getAddress(), 7); Mailsocketchat.push = false; Mailsocketchat.repeat = true; Mailsocketchat.address = addrfrom.getAddress(); if (repeatthread == null) { repeatthread = new Repeat(); repeat = new Timer(); } repeat.schedule(repeatthread, 0, 30 * 1000); System.out.println("?????"); } else if (subject.equals("list") || subject.equals("List") || subject.equals("")) { Send(addrfrom.getAddress(), 4); } else if (subject.equals("help") || subject.equals("Help") || subject.equals("")) { Send(addrfrom.getAddress(), 5); } else { if (!Mailsocketchat.push && !Mailsocketchat.repeat) { Send(addrfrom.getAddress(), 0); } else if (comment.equals("") || comment.equals(" ") || comment.equals(" ")) { Send(addrfrom.getAddress(), 5); } } } catch (IOException ioex) { System.out.println( "??????????"); } catch (MessagingException mex) { System.out.println( "??????????"); } } } }); // Check mail once in "freq" MILLIseconds int freq = 1000; //?? boolean supportsIdle = false; try { if (folder instanceof IMAPFolder) { IMAPFolder f = (IMAPFolder) folder; f.idle(); supportsIdle = true; } } catch (FolderClosedException fex) { throw fex; } catch (MessagingException mex) { supportsIdle = false; } for (;;) { if (supportsIdle && folder instanceof IMAPFolder) { IMAPFolder f = (IMAPFolder) folder; f.idle(); } else { Thread.sleep(freq); // sleep for freq milliseconds // This is to force the IMAP server to send us // EXISTS notifications. folder.getMessageCount(); } } } catch (Exception ex) { System.out.println("??????????"); } } }
From source file:davmail.imap.ImapConnection.java
protected void appendMailEnvelopeHeader(StringBuilder buffer, String[] value) { buffer.append(' '); if (value != null && value.length > 0) { try {/* www.j a v a 2s .c o m*/ String unfoldedValue = MimeUtility.unfold(value[0]); InternetAddress[] addresses = InternetAddress.parseHeader(unfoldedValue, false); if (addresses != null && addresses.length > 0) { buffer.append('('); for (InternetAddress address : addresses) { buffer.append('('); String personal = address.getPersonal(); if (personal != null) { appendEnvelopeHeaderValue(buffer, personal); } else { buffer.append("NIL"); } buffer.append(" NIL "); String mail = address.getAddress(); int atIndex = mail.indexOf('@'); if (atIndex >= 0) { buffer.append('"').append(mail.substring(0, atIndex)).append('"'); buffer.append(' '); buffer.append('"').append(mail.substring(atIndex + 1)).append('"'); } else { buffer.append("NIL NIL"); } buffer.append(')'); } buffer.append(')'); } else { buffer.append("NIL"); } } catch (AddressException e) { DavGatewayTray.warn(e); buffer.append("NIL"); } catch (UnsupportedEncodingException e) { DavGatewayTray.warn(e); buffer.append("NIL"); } } else { buffer.append("NIL"); } }
From source file:ru.org.linux.user.RegisterController.java
@RequestMapping(value = "/register.jsp", method = RequestMethod.POST) public ModelAndView doRegister(HttpServletRequest request, @Valid @ModelAttribute("form") RegisterRequest form, Errors errors, @RequestParam(required = false) String oldpass) throws Exception { HttpSession session = request.getSession(); Template tmpl = Template.getTemplate(request); boolean changeMode = "change".equals(request.getParameter("mode")); String nick;/*w w w . j av a 2 s .c om*/ if (changeMode) { if (!tmpl.isSessionAuthorized()) { throw new AccessViolationException("Not authorized"); } nick = tmpl.getNick(); } else { nick = form.getNick(); if (Strings.isNullOrEmpty(nick)) { errors.rejectValue("nick", null, " nick"); } if (nick != null && !StringUtil.checkLoginName(nick)) { errors.rejectValue("nick", null, " ? ?"); } if (nick != null && nick.length() > User.MAX_NICK_LENGTH) { errors.rejectValue("nick", null, "? ? ?"); } } String password = Strings.emptyToNull(form.getPassword()); if (password != null && password.equalsIgnoreCase(nick)) { errors.reject(null, " ? ? "); } InternetAddress mail = null; if (Strings.isNullOrEmpty(form.getEmail())) { errors.rejectValue("email", null, "? e-mail"); } else { try { mail = new InternetAddress(form.getEmail()); } catch (AddressException e) { errors.rejectValue("email", null, "? e-mail: " + e.getMessage()); } } String url = null; if (!Strings.isNullOrEmpty(form.getUrl())) { url = URLUtil.fixURL(form.getUrl()); } if (!changeMode) { if (Strings.isNullOrEmpty(password)) { errors.reject(null, " ?"); } } String name = Strings.emptyToNull(form.getName()); if (name != null) { name = StringUtil.escapeHtml(name); } String town = null; if (!Strings.isNullOrEmpty(form.getTown())) { town = StringUtil.escapeHtml(form.getTown()); } String info = null; if (!Strings.isNullOrEmpty(form.getInfo())) { info = StringUtil.escapeHtml(form.getInfo()); } if (!changeMode && !errors.hasErrors()) { captcha.checkCaptcha(request, errors); if (session.getAttribute("register-visited") == null) { logger.info("Flood protection (not visited register.jsp) " + request.getRemoteAddr()); errors.reject(null, "? , "); } } ipBlockDao.checkBlockIP(request.getRemoteAddr(), errors); boolean emailChanged = false; if (changeMode) { User user = userDao.getUser(nick); if (!user.matchPassword(oldpass)) { errors.reject(null, "? "); } user.checkAnonymous(); String newEmail = null; if (mail != null) { if (user.getEmail() != null && user.getEmail().equals(form.getEmail())) { newEmail = null; } else { if (userDao.getByEmail(mail.getAddress()) != null) { errors.rejectValue("email", null, " email ???"); } newEmail = mail.getAddress(); emailChanged = true; } } if (!errors.hasErrors()) { userDao.updateUser(user, name, url, newEmail, town, password, info); if (emailChanged) { sendEmail(tmpl, user.getNick(), mail.getAddress(), false); } } else { return new ModelAndView("register-update"); } } else { if (userDao.isUserExists(nick)) { errors.rejectValue("nick", null, " " + nick + " ??"); } if (url != null && !URLUtil.isUrl(url)) { errors.rejectValue("url", null, "? URL"); } if (mail != null && userDao.getByEmail(mail.getAddress()) != null) { errors.rejectValue("email", null, " ? e-mail ?. " + "? ? , ?? ??? ?"); } if (!errors.hasErrors()) { int userid = userDao.createUser(name, nick, password, url, mail, town, info); String logmessage = "? " + nick + " (id=" + userid + ") " + LorHttpUtils.getRequestIP(request); logger.info(logmessage); sendEmail(tmpl, nick, mail.getAddress(), true); } else { return new ModelAndView("register"); } } if (changeMode) { if (emailChanged) { String msg = " ? ?. ? ? ? email."; return new ModelAndView("action-done", "message", msg); } else { return new ModelAndView(new RedirectView("/people/" + nick + "/profile")); } } else { return new ModelAndView("action-done", "message", " ? ?. ? ? ."); } }
From source file:com.threewks.thundr.gmail.GmailMailer.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email. * @param bodyText Body text of the email. * @return MimeMessage to be used to send email. * @throws MessagingException//from ww w . ja v a2 s. co m */ protected MimeMessage createEmailWithAttachment(Set<InternetAddress> to, InternetAddress from, Set<InternetAddress> cc, Set<InternetAddress> bcc, InternetAddress replyTo, String subject, String bodyText, List<com.threewks.thundr.mail.Attachment> attachments) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); try { email.setFrom(from); if (to != null) { email.addRecipients(javax.mail.Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()])); } if (cc != null) { email.addRecipients(javax.mail.Message.RecipientType.CC, cc.toArray(new InternetAddress[cc.size()])); } if (bcc != null) { email.addRecipients(javax.mail.Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()])); } if (replyTo != null) { email.setReplyTo(new Address[] { replyTo }); } email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/html"); mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); if (attachments != null) { for (com.threewks.thundr.mail.Attachment attachment : attachments) { mimeBodyPart = new MimeBodyPart(); BasicViewRenderer renderer = new BasicViewRenderer(viewResolverRegistry); renderer.render(attachment.view()); byte[] data = renderer.getOutputAsBytes(); String attachmentContentType = renderer.getContentType(); String attachmentCharacterEncoding = renderer.getCharacterEncoding(); populateMimeBodyPart(mimeBodyPart, attachment, data, attachmentContentType, attachmentCharacterEncoding); multipart.addBodyPart(mimeBodyPart); } } email.setContent(multipart); } catch (MessagingException e) { Logger.error(e.getMessage()); Logger.error( "Failed to create email from: %s;%s, to: %s, cc: %s, bcc: %s, replyTo %s;%s, subject %s, body %s, number of attachments %d", from.getAddress(), from.getPersonal(), Transformers.InternetAddressesToString.from(to), Transformers.InternetAddressesToString.from(cc), Transformers.InternetAddressesToString.from(bcc), replyTo == null ? "null" : replyTo.getAddress(), replyTo == null ? "null" : replyTo.getPersonal(), subject, bodyText, attachments == null ? 0 : attachments.size()); throw new GmailException(e); } return email; }
From source file:com.aurel.track.util.emailHandling.MailSender.java
/** * //ww w .j a v a 2s.c o m * @param smtpMailSettings * @param internetAddressFrom * @param internetAddressesTo * @param subject * @param messageBody * @param isPlain * @param attachments * @param internetAddressesCC * @param internetAddressesBCC * @param internetAddressesReplayTo */ private void init(SMTPMailSettings smtpMailSettings, InternetAddress internetAddressFrom, InternetAddress[] internetAddressesTo, String subject, String messageBody, boolean isPlain, List<LabelValueBean> attachments, InternetAddress[] internetAddressesCC, InternetAddress[] internetAddressesBCC, InternetAddress[] internetAddressesReplayTo) { this.smtpMailSettings = smtpMailSettings; try { if (isPlain) { email = new SimpleEmail(); if (attachments != null && attachments.size() > 0) { email = new MultiPartEmail(); } } else { email = new HtmlEmail(); } if (LOGGER.isTraceEnabled()) { email.setDebug(true); } email.setHostName(smtpMailSettings.getHost()); email.setSmtpPort(smtpMailSettings.getPort()); email.setCharset(smtpMailSettings.getMailEncoding() != null ? smtpMailSettings.getMailEncoding() : DEFAULTENCODINGT); if (timeout != null) { email.setSocketConnectionTimeout(timeout); email.setSocketTimeout(timeout); } if (smtpMailSettings.isReqAuth()) { email = setAuthMode(email); } email = setSecurityMode(email); for (int i = 0; i < internetAddressesTo.length; ++i) { email.addTo(internetAddressesTo[i].getAddress(), internetAddressesTo[i].getPersonal()); } if (internetAddressesCC != null) { for (int i = 0; i < internetAddressesCC.length; ++i) { email.addCc(internetAddressesCC[i].getAddress(), internetAddressesCC[i].getPersonal()); } } if (internetAddressesBCC != null) { for (int i = 0; i < internetAddressesBCC.length; ++i) { email.addBcc(internetAddressesBCC[i].getAddress(), internetAddressesBCC[i].getPersonal()); } } if (internetAddressesReplayTo != null) { for (int i = 0; i < internetAddressesReplayTo.length; ++i) { email.addReplyTo(internetAddressesReplayTo[i].getAddress(), internetAddressesReplayTo[i].getPersonal()); } } email.setFrom(internetAddressFrom.getAddress(), internetAddressFrom.getPersonal()); email.setSubject(subject); String cid = null; if (isPlain) { email.setMsg(messageBody); } else { if (messageBody.contains("cid:$$CID$$")) { URL imageURL = null; InputStream in = null; in = MailSender.class.getClassLoader().getResourceAsStream("tracklogo.gif"); if (in != null) { imageURL = new URL(ApplicationBean.getInstance().getServletContext().getResource("/") + "logoAction.action?type=m"); DataSource ds = new ByteArrayDataSource(in, "image/" + "gif"); cid = ((HtmlEmail) email).embed(ds, "Genji"); } else { String theResource = "/WEB-INF/classes/resources/MailTemplates/tracklogo.gif"; imageURL = ApplicationBean.getInstance().getServletContext().getResource(theResource); cid = ((HtmlEmail) email).embed(imageURL, "Genji"); } messageBody = messageBody.replaceFirst("\\$\\$CID\\$\\$", cid); } Set<String> attachSet = new HashSet<String>(); messageBody = MailImageBL.replaceInlineImages(messageBody, attachSet); if (!attachSet.isEmpty()) { Iterator<String> it = attachSet.iterator(); while (it.hasNext()) { String key = it.next(); StringTokenizer st = new StringTokenizer(key, "_"); String workItemIDStr = st.nextToken(); String attachmentKeyStr = st.nextToken(); TAttachmentBean attachmentBean = null; try { attachmentBean = AttachBL.loadAttachment(Integer.valueOf(attachmentKeyStr), Integer.valueOf(workItemIDStr), true); } catch (Exception ex) { } if (attachmentBean != null) { String fileName = attachmentBean.getFullFileNameOnDisk(); File file = new File(fileName); InputStream is = new FileInputStream(file); DataSource ds = new ByteArrayDataSource(is, "image/" + "gif"); cid = ((HtmlEmail) email).embed(ds, key); messageBody = messageBody.replaceAll("cid:" + key, "cid:" + cid); } } } ((HtmlEmail) email).setHtmlMsg(messageBody); } if (attachments != null && !attachments.isEmpty()) { includeAttachments(attachments); } } catch (Exception e) { LOGGER.error("Something went wrong trying to assemble an e-mail: " + e.getMessage()); } }
From source file:org.sakaiproject.email.impl.BasicEmailService.java
/** * fix up From and ReplyTo if we need it to be from Postmaster *//*from w w w . j a v a 2 s. c om*/ private void checkFrom(MimeMessage msg) { String sendFromSakai = serverConfigurationService.getString(MAIL_SENDFROMSAKAI, "true"); String sendExceptions = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_EXCEPTIONS, null); InternetAddress from = null; InternetAddress[] replyTo = null; try { Address[] fromA = msg.getFrom(); if (fromA == null || fromA.length == 0) { M_log.info("message from missing"); return; } else if (fromA.length > 1) { M_log.info("message from more than 1"); return; } else if (fromA instanceof InternetAddress[]) { from = (InternetAddress) fromA[0]; } else { M_log.info("message from not InternetAddress"); return; } Address[] replyToA = msg.getReplyTo(); if (replyToA == null) replyTo = null; else if (replyToA instanceof InternetAddress[]) replyTo = (InternetAddress[]) replyToA; else { M_log.info("message replyto isn't internet address"); return; } // should we replace from address with a Sakai address? if (sendFromSakai != null && !sendFromSakai.equalsIgnoreCase("false")) { // exceptions -- addresses to leave alone. Our own addresses are always exceptions. // you can also configure a regexp of exceptions. if (!from.getAddress().toLowerCase() .endsWith("@" + serverConfigurationService.getServerName().toLowerCase()) && (sendExceptions == null || sendExceptions.equals("") || !from.getAddress().toLowerCase().matches(sendExceptions))) { // not an exception. do the replacement. // First, decide on the replacement address. The config variable // may be the replacement address. If not, use postmaster if (sendFromSakai.indexOf("@") < 0) sendFromSakai = POSTMASTER + "@" + serverConfigurationService.getServerName(); // put the original from into reply-to, unless a replyto exists if (replyTo == null || replyTo.length == 0 || replyTo[0].getAddress().equals("")) { replyTo = new InternetAddress[1]; replyTo[0] = from; msg.setReplyTo(replyTo); } // for some reason setReplyTo doesn't work, though setFrom does. Have to create the // actual header line if (msg.getHeader(EmailHeaders.REPLY_TO) == null) msg.addHeader(EmailHeaders.REPLY_TO, from.getAddress()); // and use the new from address // biggest issue is the "personal address", i.e. the comment text String origFromText = from.getPersonal(); String origFromAddress = from.getAddress(); String fromTextPattern = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_FROMTEXT, "{}"); String fromText = null; if (origFromText != null && !origFromText.equals("")) fromText = fromTextPattern.replace("{}", origFromText + " (" + origFromAddress + ")"); else fromText = fromTextPattern.replace("{}", origFromAddress); from = new InternetAddress(sendFromSakai); try { from.setPersonal(fromText); } catch (Exception e) { } msg.setFrom(from); } } } catch (javax.mail.internet.AddressException e) { M_log.info("checkfrom address exception " + e); } catch (javax.mail.MessagingException e) { M_log.info("checkfrom messaging exception " + e); } }
From source file:com.sonicle.webtop.core.CoreManager.java
/** * Returns a list of recipients beloging to a specified type. * @param fieldType The desired recipient type. * @param sourceIds A collection of sources in which look for. * @param queryText A text to filter out returned results. * @param max Max number of results./* w ww. ja va2s . c om*/ * @return * @throws WTException */ public List<Recipient> listProviderRecipients(RecipientFieldType fieldType, Collection<String> sourceIds, String queryText, int max) throws WTException { CoreServiceSettings css = new CoreServiceSettings(CoreManifest.ID, getTargetProfileId().getDomainId()); ArrayList<Recipient> items = new ArrayList<>(); boolean autoProviderEnabled = css.getRecipientAutoProviderEnabled(); int remaining = max; for (String soId : sourceIds) { List<Recipient> recipients = null; if (StringUtils.equals(soId, RECIPIENT_PROVIDER_AUTO_SOURCE_ID)) { if (!autoProviderEnabled) continue; if (!fieldType.equals(RecipientFieldType.LIST)) { recipients = new ArrayList<>(); //TODO: Find a way to handle other RecipientFieldTypes if (fieldType.equals(RecipientFieldType.EMAIL)) { final List<OServiceStoreEntry> entries = listServiceStoreEntriesByQuery(SERVICE_ID, "recipients", queryText, remaining); for (OServiceStoreEntry entry : entries) { final InternetAddress ia = InternetAddressUtils.toInternetAddress(entry.getValue()); if (ia != null) recipients.add(new Recipient(RECIPIENT_PROVIDER_AUTO_SOURCE_ID, lookupResource(getLocale(), CoreLocaleKey.INTERNETRECIPIENT_AUTO), RECIPIENT_PROVIDER_AUTO_SOURCE_ID, ia.getPersonal(), ia.getAddress())); } } } } else if (StringUtils.equals(soId, RECIPIENT_PROVIDER_WEBTOP_SOURCE_ID)) { if (!fieldType.equals(RecipientFieldType.LIST)) { recipients = new ArrayList<>(); //TODO: Find a way to handle other RecipientFieldTypes if (fieldType.equals(RecipientFieldType.EMAIL)) { List<OUser> users = listUsers(true); for (OUser user : users) { UserProfile.Data userData = WT .getUserData(new UserProfileId(user.getDomainId(), user.getUserId())); if (userData != null) { if (StringUtils.containsIgnoreCase(user.getDisplayName(), queryText) || StringUtils .containsIgnoreCase(userData.getPersonalEmailAddress(), queryText)) recipients.add(new Recipient(RECIPIENT_PROVIDER_WEBTOP_SOURCE_ID, lookupResource(getLocale(), CoreLocaleKey.INTERNETRECIPIENT_WEBTOP), RECIPIENT_PROVIDER_AUTO_SOURCE_ID, user.getDisplayName(), userData.getPersonalEmailAddress())); } } } } } else { final RecipientsProviderBase provider = getProfileRecipientsProviders().get(soId); if (provider == null) continue; try { recipients = provider.getRecipients(fieldType, queryText, remaining); } catch (Throwable t) { logger.error("Error calling RecipientProvider [{}]", t, soId); } if (recipients == null) continue; } if (recipients != null) for (Recipient recipient : recipients) { remaining--; if (remaining < 0) break; recipient.setSource(soId); // Force composed id! items.add(recipient); } if (remaining <= 0) break; } return items; }
From source file:com.sonicle.webtop.core.app.WebTopManager.java
private OUser doUserInsert(Connection con, ODomain domain, UserEntity user) throws DAOException, WTException { UserDAO udao = UserDAO.getInstance(); UserInfoDAO uidao = UserInfoDAO.getInstance(); InternetAddress email = InternetAddressUtils.toInternetAddress(user.getUserId(), domain.getInternetName(), null);// w ww. j av a 2 s.c o m if (email == null) throw new WTException("Cannot create a valid email address [{0}, {1}]", user.getUserId(), domain.getInternetName()); // Insert User record logger.debug("Inserting user"); OUser ouser = new OUser(); ouser.setDomainId(domain.getDomainId()); ouser.setUserId(user.getUserId()); ouser.setEnabled(user.getEnabled()); ouser.setUserUid(IdentifierUtils.getUUID()); ouser.setDisplayName(user.getDisplayName()); ouser.setSecret(generateSecretKey()); udao.insert(con, ouser); // Insert UserInfo record logger.debug("Inserting userInfo"); OUserInfo oui = new OUserInfo(); oui.setDomainId(domain.getDomainId()); oui.setUserId(user.getUserId()); oui.setFirstName(user.getFirstName()); oui.setLastName(user.getLastName()); oui.setEmail(email.getAddress()); uidao.insert(con, oui); logger.debug("Inserting groups associations"); HashSet<String> usedGroupUids = new HashSet<>(); for (AssignedGroup assiGroup : user.getAssignedGroups()) { final String groupUid = groupToUid(new UserProfileId(user.getDomainId(), assiGroup.getGroupId())); if (!usedGroupUids.contains(groupUid)) { // Due to built-in assigned groups, collection of assigned // groups can contain duplicates; so skip them. doInsertUserAssociation(con, ouser.getUserUid(), groupUid); usedGroupUids.add(groupUid); } } logger.debug("Inserting roles associations"); HashSet<String> usedRoleUids = new HashSet<>(); for (AssignedRole assiRole : user.getAssignedRoles()) { final String roleUid = assiRole.getRoleUid(); if (!usedRoleUids.contains(roleUid)) { // Due to built-in assigned roles, collection of assigned // roles can contain duplicates; so skip them. doInsertRoleAssociation(con, ouser.getUserUid(), roleUid); usedRoleUids.add(roleUid); } } // Insert permissions logger.debug("Inserting permissions"); for (ORolePermission perm : user.getPermissions()) { doInsertPermission(con, ouser.getUserUid(), perm.getServiceId(), perm.getKey(), perm.getAction(), "*"); } for (ORolePermission perm : user.getServicesPermissions()) { doInsertPermission(con, ouser.getUserUid(), CoreManifest.ID, "SERVICE", ServicePermission.ACTION_ACCESS, perm.getInstance()); } return ouser; }
From source file:davmail.exchange.ExchangeSession.java
/** * Send message in reader to recipients. * Detect visible recipients in message body to determine bcc recipients * * @param rcptToRecipients recipients list * @param mimeMessage mime message/*from w ww . j av a2s. c o m*/ * @throws IOException on error * @throws MessagingException on error */ public void sendMessage(List<String> rcptToRecipients, MimeMessage mimeMessage) throws IOException, MessagingException { // detect duplicate send command String messageId = mimeMessage.getMessageID(); if (lastSentMessageId != null && lastSentMessageId.equals(messageId)) { LOGGER.debug("Dropping message id " + messageId + ": already sent"); return; } lastSentMessageId = messageId; convertResentHeader(mimeMessage, "From"); convertResentHeader(mimeMessage, "To"); convertResentHeader(mimeMessage, "Cc"); convertResentHeader(mimeMessage, "Bcc"); convertResentHeader(mimeMessage, "Message-Id"); mimeMessage.removeHeader("From"); // remove visible recipients from list Set<String> visibleRecipients = new HashSet<String>(); List<InternetAddress> recipients = getAllRecipients(mimeMessage); for (InternetAddress address : recipients) { visibleRecipients.add((address.getAddress().toLowerCase())); } for (String recipient : rcptToRecipients) { if (!visibleRecipients.contains(recipient.toLowerCase())) { mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipient)); } } sendMessage(mimeMessage); }
From source file:com.sonicle.webtop.contacts.ContactsManager.java
private ReminderEmail createAnniversaryEmailReminder(Locale locale, InternetAddress recipient, boolean birthday, VContact contact, DateTime date) { String type = (birthday) ? "birthday" : "anniversary"; String resKey = (birthday) ? ContactsLocale.REMINDER_TITLE_BIRTHDAY : ContactsLocale.REMINDER_TITLE_ANNIVERSARY; String fullName = BaseContact.buildFullName(contact.getFirstname(), contact.getLastname()); String title = MessageFormat.format(lookupResource(locale, resKey), StringUtils.trim(fullName)); String subject = NotificationHelper.buildSubject(locale, SERVICE_ID, title); String body = null;// www. j a v a 2 s. co m try { body = TplHelper.buildAnniversaryEmail(locale, birthday, recipient.getAddress(), fullName); } catch (IOException | TemplateException ex) { logger.error("Error building anniversary email", ex); } ReminderEmail alert = new ReminderEmail(SERVICE_ID, contact.getCategoryProfileId(), type, contact.getContactId().toString()); alert.setSubject(subject); alert.setBody(body); return alert; }