List of usage examples for javax.mail.internet InternetAddress getAddress
public String getAddress()
From source file:edu.stanford.muse.email.EmailFetcherStats.java
/** * intern a bunch of addrs, to save memory * * @throws UnsupportedEncodingException/*from w w w.ja va 2 s . c o m*/ */ private static void internAddressList(Address[] addrs) throws UnsupportedEncodingException { if (addrs == null) return; for (Address a : addrs) { if (a instanceof InternetAddress) { InternetAddress ia = (InternetAddress) a; String address = ia.getAddress(), personal = ia.getPersonal(); if (address != null) ia.setAddress(InternTable.intern(address)); if (personal != null) ia.setPersonal(InternTable.intern(personal)); } } }
From source file:nl.strohalm.cyclos.utils.MailHandler.java
private void doSend(final String subject, final InternetAddress replyTo, final InternetAddress to, final String body, final boolean isHTML, final boolean throwException) { if (to == null || StringUtils.isEmpty(to.getAddress())) { return;//from ww w. ja v a 2 s. co m } final LocalSettings localSettings = settingsService.getLocalSettings(); final MailSettings mailSettings = settingsService.getMailSettings(); final JavaMailSender mailSender = mailSettings.getMailSender(); final MimeMessage message = mailSender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message, localSettings.getCharset()); try { helper.setFrom(getSystemAddress()); if (replyTo != null) { helper.setReplyTo(replyTo); } helper.setTo(to); helper.setSubject(subject); helper.setText(body, isHTML); mailSender.send(message); } catch (final MessagingException e) { if (throwException) { throw new MailSendingException(subject, e); } // Store the current Exception CurrentTransactionData.setMailError(new MailSendingException(subject, e)); } catch (final MailException e) { if (throwException) { throw new MailSendingException(subject, e); } CurrentTransactionData.setMailError(new MailSendingException(subject, e)); } }
From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java
@Override public boolean execute(ExecutionContext context) { bodyContent = ""; boolean copyMessage = Boolean.parseBoolean(Framework.getProperty(COPY_MESSAGE, "false")); try {//from www. j av a 2s . co m Message originalMessage = context.getMessage(); if (log.isDebugEnabled()) { log.debug("Transforming message, original subject: " + originalMessage.getSubject()); } // fully load the message before trying to parse to // override most of server bugs, see // http://java.sun.com/products/javamail/FAQ.html#imapserverbug Message message; if (originalMessage instanceof MimeMessage && copyMessage) { message = new MimeMessage((MimeMessage) originalMessage); if (log.isDebugEnabled()) { log.debug("Transforming message after full load: " + message.getSubject()); } } else { // stuck with the original one message = originalMessage; } // Subject String subject = message.getSubject(); if (subject != null) { subject = subject.trim(); } if (subject == null || "".equals(subject)) { subject = "<Unknown>"; } context.put(SUBJECT_KEY, subject); // Sender try { Address[] from = message.getFrom(); String sender = null; String senderEmail = null; if (from != null) { Address addr = from[0]; if (addr instanceof InternetAddress) { InternetAddress iAddr = (InternetAddress) addr; senderEmail = iAddr.getAddress(); sender = iAddr.getPersonal() + " <" + senderEmail + ">"; } else { sender += addr.toString(); senderEmail = sender; } } context.put(SENDER_KEY, sender); context.put(SENDER_EMAIL_KEY, senderEmail); } catch (AddressException ae) { // try to parse sender from header instead String[] values = message.getHeader("From"); if (values != null) { context.put(SENDER_KEY, values[0]); } } // Sending date context.put(SENDING_DATE_KEY, message.getSentDate()); // Recipients try { Address[] to = message.getRecipients(Message.RecipientType.TO); Collection<String> recipients = new ArrayList<String>(); if (to != null) { for (Address addr : to) { if (addr instanceof InternetAddress) { InternetAddress iAddr = (InternetAddress) addr; if (iAddr.getPersonal() != null) { recipients.add(iAddr.getPersonal() + " <" + iAddr.getAddress() + ">"); } else { recipients.add(iAddr.getAddress()); } } else { recipients.add(addr.toString()); } } } context.put(RECIPIENTS_KEY, recipients); } catch (AddressException ae) { // try to parse recipient from header instead Collection<String> recipients = getHeaderValues(message, Message.RecipientType.TO.toString()); context.put(RECIPIENTS_KEY, recipients); } // CC recipients try { Address[] toCC = message.getRecipients(Message.RecipientType.CC); Collection<String> ccRecipients = new ArrayList<String>(); if (toCC != null) { for (Address addr : toCC) { if (addr instanceof InternetAddress) { InternetAddress iAddr = (InternetAddress) addr; ccRecipients.add(iAddr.getPersonal() + " " + iAddr.getAddress()); } else { ccRecipients.add(addr.toString()); } } } context.put(CC_RECIPIENTS_KEY, ccRecipients); } catch (AddressException ae) { // try to parse ccRecipient from header instead Collection<String> ccRecipients = getHeaderValues(message, Message.RecipientType.CC.toString()); context.put(CC_RECIPIENTS_KEY, ccRecipients); } String[] messageIdHeader = message.getHeader("Message-ID"); if (messageIdHeader != null) { context.put(MailCoreConstants.MESSAGE_ID_KEY, messageIdHeader[0]); } MimetypeRegistry mimeService = (MimetypeRegistry) context.getInitialContext().get(MIMETYPE_SERVICE_KEY); List<Blob> blobs = new ArrayList<Blob>(); context.put(ATTACHMENTS_KEY, blobs); // String[] cte = message.getHeader("Content-Transfer-Encoding"); // process content getAttachmentParts(message, subject, mimeService, context); context.put(TEXT_KEY, bodyContent); return true; } catch (MessagingException | IOException e) { log.error(e, e); } return false; }
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);//w w w . jav a2 s . 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:org.agnitas.beans.impl.MediatypeEmailImpl.java
public String getFromAdr() throws Exception { InternetAddress tmpFrom = new InternetAddress(this.fromEmail, this.fromFullname, charset); //problems with coding //return AgnUtils.propertySaveString(tmpFrom.toString()); String adr = ""; adr = tmpFrom.getPersonal() + " <" + tmpFrom.getAddress() + ">"; return adr;/*from w ww . j ava2 s. c o m*/ }
From source file:com.zimbra.cs.mime.Mime.java
/** * Remove all email addresses in rcpts from To/Cc/Bcc headers of a * MimeMessage.// ww w . jav a2s. co m * @param mm * @param rcpts * @throws MessagingException */ public static void removeRecipients(MimeMessage mm, String[] rcpts) throws MessagingException { for (RecipientType rcptType : sRcptTypes) { Address[] addrs = mm.getRecipients(rcptType); if (addrs == null) continue; ArrayList<InternetAddress> list = new ArrayList<InternetAddress>(addrs.length); for (int j = 0; j < addrs.length; j++) { InternetAddress inetAddr = (InternetAddress) addrs[j]; String addr = inetAddr.getAddress(); boolean match = false; for (int k = 0; k < rcpts.length; k++) if (addr.equalsIgnoreCase(rcpts[k])) match = true; if (!match) list.add(inetAddr); } if (list.size() < addrs.length) { InternetAddress[] newRcpts = new InternetAddress[list.size()]; list.toArray(newRcpts); mm.setRecipients(rcptType, newRcpts); } } }
From source file:com.aurel.track.item.SendItemEmailAction.java
@Override public void prepare() throws Exception { locale = (Locale) session.get(Constants.LOCALE_KEY); personBean = (TPersonBean) session.get(Constants.USER_KEY); if (personBean == null) { return;/* w w w . ja va2 s.co m*/ } personID = personBean.getObjectID(); workItemContext = ItemBL.editWorkItem(workItemID, personID, locale, true); projectBean = SendItemEmailBL.getProject(workItemContext.getWorkItemBean().getProjectID()); fromAddressList = new ArrayList<LabelValueBean>(); String userAddr = personBean.getEmail(); LabelValueBean addres = new LabelValueBean(); addres.setLabel(personBean.getFullName() + "<" + userAddr + ">"); addres.setValue(userAddr); fromAddressList.add(addres); String defaultFrom = userAddr; String projectTrackSystemEmail = PropertiesHelper.getProperty(projectBean.getMoreProperties(), TProjectBean.MOREPPROPS.TRACK_EMAIL_PROPERTY); //String projectEmailPersonName=PropertiesHelper.getProperty(projectBean.getMoreProps(), TProjectBean.MOREPPROPS.EMAIL_PERSONAL_NAME); boolean useTrackFromAddressDisplay = "true".equalsIgnoreCase(PropertiesHelper.getProperty( projectBean.getMoreProperties(), TProjectBean.MOREPPROPS.USE_TRACK_FROM_ADDRESS_DISPLAY)); String projectLocalized = projectBean.getLabel();// FieldRuntimeBL.getLocalizedDefaultFieldLabel(SystemFields.PROJECT, locale); if (projectTrackSystemEmail != null && projectTrackSystemEmail.length() > 0) { //verify address try { InternetAddress tmp = new InternetAddress(projectTrackSystemEmail); LOGGER.debug(tmp.getAddress() + " is valid!"); addres = new LabelValueBean(); addres.setLabel(projectLocalized + "<" + projectTrackSystemEmail + ">"); addres.setValue(projectTrackSystemEmail); fromAddressList.add(addres); if (useTrackFromAddressDisplay) { defaultFrom = projectTrackSystemEmail; } } catch (AddressException e) { LOGGER.error("The email:'" + projectTrackSystemEmail + "' set on this project is invalid!"); } } String emailAddress = ApplicationBean.getInstance().getSiteBean().getSendFrom().getEmail(); if (emailAddress != null) { addres = new LabelValueBean(); addres.setLabel(ApplicationBean.getInstance().getSiteBean().getSendFrom().getFullName() + "<" + emailAddress + ">"); addres.setValue(emailAddress); fromAddressList.add(addres); if (!useTrackFromAddressDisplay && ApplicationBean.getInstance().getSiteBean() .getUseTrackFromAddressDisplay().equals(TSiteBean.SEND_FROM_MODE.SYSTEM)) { defaultFrom = emailAddress; } } if (from == null) { from = defaultFrom; } submitterEmail = workItemContext.getWorkItemBean().getSubmitterEmail(); attachmentsList = new ArrayList<IntegerStringBean>(); List attachListDB = null; if (workItemID == null) { attachListDB = workItemContext.getAttachmentsList(); } else { attachListDB = AttachBL.getAttachments(workItemID); } if (attachListDB != null) { for (int i = 0; i < attachListDB.size(); i++) { TAttachmentBean attachmentBean = (TAttachmentBean) attachListDB.get(i); attachmentsList .add(new IntegerStringBean(attachmentBean.getFileName(), attachmentBean.getObjectID())); } } String part0 = SendItemEmailBL.getMarker(workItemContext.getWorkItemBean(), locale); /*String part0 = LocalizeUtil.getParametrizedString("item.mail.subjectStructure.part0", new Object[] {workItemID}, locale);*/ subjectReadolnyPart = part0 + "[" + projectBean.getLabel() + "]"; }
From source file:com.sonicle.webtop.core.app.OTPManager.java
private byte[] generateGoogleAuthQRCode(UserProfileId pid, OTPKey otp, int size) throws WTException { ODomain domain = wta.getWebTopManager().getDomain(pid.getDomainId()); if (domain == null) throw new WTException("Domain not found [{0}]", pid.getDomainId()); String issuer = URIUtils/*from w w w .j a v a 2 s. com*/ .encodeQuietly(MessageFormat.format("{0} ({1})", WT.getPlatformName(), domain.getInternetName())); InternetAddress ia = InternetAddressUtils.toInternetAddress(pid.getUserId(), domain.getInternetName(), null); if (ia == null) throw new WTException("Unable to build account address"); String uri = GoogleAuthOTPKey.buildAuthenticatorURI(issuer, otp.getKey(), ia.getAddress()); logger.debug("Generating OPT QRCode for {}", uri); return QRCode.from(uri).withSize(size, size).stream().toByteArray(); }
From source file:edu.stanford.muse.webapp.JSPHelper.java
public static Pair<String, String> getNameAndURL(InternetAddress a, AddressBook addressBook) { String s = a.getAddress(); if (s == null) s = a.getPersonal();/* w ww .java 2s .c o m*/ 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:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java
/** * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME * format).//from www. j a v a2 s . c o m * * @param pFrom : from field that will appear in the email header. * @param personalName : * @see {@link InternetAddress} * @param pTo : the email target destination. * @param pSubject : the subject of the email. * @param pMessage : the message or payload of the email. */ private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage, boolean htmlFormat) throws NotificationServerException { // retrieves system properties and set up Delivery Status Notification // @see RFC1891 Properties properties = System.getProperties(); properties.put("mail.smtp.host", getMailServer()); properties.put("mail.smtp.auth", String.valueOf(isAuthenticated())); javax.mail.Session session = javax.mail.Session.getInstance(properties, null); session.setDebug(isDebug()); // print on the console all SMTP messages. Transport transport = null; try { InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName); InternetAddress replyToAddress = null; InternetAddress[] toAddress = null; // parsing destination address for compliance with RFC822 try { toAddress = InternetAddress.parse(pTo, false); if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom) && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) { replyToAddress = new InternetAddress(pFrom, false); if (StringUtil.isDefined(personalName)) { replyToAddress.setPersonal(personalName, CharEncoding.UTF_8); } } } catch (AddressException e) { SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "From = " + pFrom + ", To = " + pTo); } MimeMessage email = new MimeMessage(session); email.setFrom(fromAddress); if (replyToAddress != null) { email.setReplyTo(new InternetAddress[] { replyToAddress }); } email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); email.setHeader("Precedence", "list"); email.setHeader("List-ID", fromAddress.getAddress()); String subject = pSubject; if (subject == null) { subject = ""; } String content = pMessage; if (content == null) { content = ""; } email.setSubject(subject, CharEncoding.UTF_8); if (content.toLowerCase().contains("<html>") || htmlFormat) { email.setContent(content, "text/html; charset=\"UTF-8\""); } else { email.setText(content, CharEncoding.UTF_8); } email.setSentDate(new Date()); // create a Transport connection (TCP) if (isSecure()) { transport = session.getTransport(SECURE_TRANSPORT); } else { transport = session.getTransport(SIMPLE_TRANSPORT); } if (isAuthenticated()) { SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin()); transport.connect(getMailServer(), getPort(), getLogin(), getPassword()); } else { transport.connect(); } transport.sendMessage(email, toAddress); } catch (MessagingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (UnsupportedEncodingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (Exception e) { throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR, "smtp.EX_CANT_SEND_SMTP_MESSAGE", e); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e); } } } }