List of usage examples for javax.mail.internet InternetAddress getPersonal
public String getPersonal()
From source file:com.duroty.application.mail.manager.SendManager.java
/** * DOCUMENT ME!// www . j a va 2 s .co 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); } }
From source file:com.duroty.application.mail.manager.SendManager.java
/** * DOCUMENT ME!/*from w w w . j a va 2 s. co m*/ * * @param hsession DOCUMENT ME! * @param session DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param identity 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 send(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); } } } String mid = getId(); 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()); } } } else { email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); } 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.saveSentMessage(mid, mime, user); Thread thread = new Thread(new SendMessageThread(email)); thread.start(); } 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); } }
From source file:org.agnitas.webservice.EmmWebservice.java
/** * Method for creating a new email-mailing. * This only creates the mailing, use "insertContent" to fill in the Text and "sendMailing" to send out the email * @param username Username from ws_admin_tbl * @param password Password from ws_admin_tbl * @param shortname Name for the mailing, visible in OpenEMM * Not visible to the recipients of the mailing * @param description Description (max. 1000 Chars) for the mailing, visible in OpenEMM * Not visible to the recipients of the mailing * @param mailinglistID Mailinglist-Id, must exist in OpenEMM * @param targetID Target group id.// w w w . j av a 2 s . com * Possible values: * ==0: All subscribers from given mailinglist * >0: An existing target group id * @param mailingType Type of mailing. * * Possible values: * 0 == normal mailing * 1 == Event-based mailing * 2 == Rule-based mailing (like automated birthday-mailings) * * If unsure, say: "0" * @param templateID Template to be used for creation of the mailing. * Can be every existing template- or mailing-id from OpenEMM or zero for no template. * * If no template is used, to content blocks are available for insertContent are "emailText" and "emailHtml" * @param emailSubject Subject-line for the email * @param emailSender Sender-address for email. * Can be a simple email-address like <CODE>info@agnitas.de</CODE> or with a given realname on the form: * <CODE>"AGNITAS AG" <info@agnitas.de></CODE> * @param emailCharset Charater-set to be used for encoding the email. * Any character-set JDK 1.4 knows is allowed. * Common value is "iso-8859-1" * @param emailLinefeed Automated linefeed in text version of the email. * @param emailFormat Format of email. * * Possible values: * 0 == only text * 1 == Online-HTML (Multipart) * 2 == Offline-HTML (Multipart+embedded graphics) * * If unsure, say "2" * @return Id of created mailing or 0 * @throws java.rmi.RemoteException necessary for Apache Axis */ public int newEmailMailing(java.lang.String username, java.lang.String password, java.lang.String shortname, java.lang.String description, int mailinglistID, StringArrayType targetID, int mailingType, int templateID, java.lang.String emailSubject, java.lang.String emailSender, java.lang.String emailCharset, int emailLinefeed, int emailFormat) throws java.rmi.RemoteException { ApplicationContext con = getWebApplicationContext(); int result = 0; MailingDao mDao = (MailingDao) con.getBean("MailingDao"); Mailing aMailing = (Mailing) con.getBean("Mailing"); MediatypeEmail paramEmail = null; MessageContext msct = MessageContext.getCurrentContext(); if (!authenticateUser(msct, username, password, 1)) { return result; } aMailing.setCompanyID(1); aMailing.setId(0); aMailing.setMailTemplateID(templateID); if (aMailing.getMailTemplateID() != 0) { //load Template aMailing = loadTemplate(aMailing, mDao, con); } aMailing.setDescription(description); aMailing.setShortname(shortname); aMailing.setCompanyID(1); if (aMailing.getMailTemplateID() == 0 || mailinglistID != 0) { aMailing.setMailinglistID(mailinglistID); } if (aMailing.getMailTemplateID() == 0 || Integer.valueOf(targetID.getX(0)).intValue() != 0) { Collection targetGroup = new ArrayList(); for (int i = 0; i < targetID.getX().length; i++) { int target = Integer.valueOf(targetID.getX(i)).intValue(); aMailing.setTargetID(target); targetGroup.add(target); } aMailing.setTargetGroups(targetGroup); } if (aMailing.getMailTemplateID() == 0) { aMailing.setMailingType(mailingType); } paramEmail = aMailing.getEmailParam(); if (paramEmail == null) { paramEmail = (MediatypeEmail) con.getBean("MediatypeEmail"); paramEmail.setCompanyID(1); paramEmail.setMailingID(aMailing.getId()); } paramEmail.setStatus(Mediatype.STATUS_ACTIVE); paramEmail.setSubject(emailSubject); try { if (aMailing.getMailTemplateID() == 0 && !emailSender.trim().equalsIgnoreCase("")) { InternetAddress adr = new InternetAddress(emailSender); paramEmail.setFromEmail(adr.getAddress()); paramEmail.setFromFullname(adr.getPersonal()); } } catch (Exception e) { AgnUtils.logger().error("Error in sender address"); } if (aMailing.getMailTemplateID() == 0) { paramEmail.setCharset(emailCharset); paramEmail.setMailFormat(emailFormat); paramEmail.setLinefeed(emailLinefeed); } paramEmail.setPriority(1); paramEmail.setOnepixel(MediatypeEmail.ONEPIXEL_BOTTOM); Map mediatypes = aMailing.getMediatypes(); mediatypes.put(new Integer(0), paramEmail); aMailing.setMediatypes(mediatypes); try { if (aMailing.getMailTemplateID() == 0) { MailingComponent comp = null; comp = (MailingComponent) con.getBean("MailingComponent"); comp.setCompanyID(1); comp.setComponentName("agnText"); comp.setType(MailingComponent.TYPE_TEMPLATE); comp.setEmmBlock("[agnDYN name=\"emailText\"/]"); comp.setMimeType("text/plain"); aMailing.addComponent(comp); comp = (MailingComponent) con.getBean("MailingComponent"); comp.setCompanyID(1); comp.setComponentName("agnHtml"); comp.setType(MailingComponent.TYPE_TEMPLATE); comp.setEmmBlock("[agnDYN name=\"emailHtml\"/]"); comp.setMimeType("text/html"); aMailing.addComponent(comp); } aMailing.buildDependencies(true, con); mDao.saveMailing(aMailing); result = aMailing.getId(); } catch (Exception e) { AgnUtils.logger().info("Error in create mailing id: " + aMailing.getId() + " msg: " + e); result = 0; } return result; }
From source file:org.agnitas.webservice.EmmWebservice.java
/** * Method for creating a new email-mailing. * This only creates the Mailing, use "insertContent" to fill in the Text and "sendMailing" to send out the email * @param username Username from ws_admin_tbl * @param password Password from ws_admin_tbl * @param shortname Name for the mailing, visible in OpenEMM * Not visible to the recipients of the mailing * @param description Description (max. 1000 Chars) for the mailing, visible in OpenEMM * Not visible to the recipients of the mailing * @param mailinglistID Mailinglist-id, must exist in OpenEMM * @param targetID Target group id.// w w w. jav a 2 s . c o m * Possible values: * ==0: All subscribers from given mailinglist * >0: An existing target group id * @param mailingType Type of mailing. * * Possible values: * 0 == normal mailing * 1 == Event-based mailing * 2 == Rule-based mailing (like automated birthday-mailings) * * If unsure, say: "0" * @param templateID Template to be used for mailing creation. * Can be every existing template- or mailing-id from OpenEMM or zero for no template. * * If no template is used, to content blocks are available for insertContent are "emailText" and "emailHtml" * @param emailSubject Subject-line for the email * @param emailSender Sender-address for email. * Can be a simple email-address like <CODE>info@agnitas.de</CODE> or with a given realname on the form: * <CODE>"AGNITAS AG" <info@agnitas.de></CODE> * @param emailReply Reply-to-address for the email * @param emailCharset Charater-set to be used for encoding the email. * Any character-set JDK 1.4 knows is allowed. * Common value is "iso-8859-1" * @param emailLinefeed Automated linefeed in text version of the email. * @param emailFormat Format of email. * * Possible values: * 0 == only text * 1 == Online-HTML (Multipart) * 2 == Offline-HTML (Multipart+embedded graphics) * * If unsure, say "2" * @return ID of created mailing or 0 * @throws java.rmi.RemoteException necessary for Apache Axis */ public int newEmailMailingWithReply(java.lang.String username, java.lang.String password, java.lang.String shortname, java.lang.String description, int mailinglistID, StringArrayType targetID, int mailingType, int templateID, java.lang.String emailSubject, java.lang.String emailSender, java.lang.String emailReply, java.lang.String emailCharset, int emailLinefeed, int emailFormat) throws java.rmi.RemoteException { ApplicationContext con = getWebApplicationContext(); int result = 0; MailingDao mDao = (MailingDao) con.getBean("MailingDao"); Mailing aMailing = (Mailing) con.getBean("Mailing"); MediatypeEmail paramEmail = null; MessageContext msct = MessageContext.getCurrentContext(); if (!authenticateUser(msct, username, password, 1)) { return result; } aMailing.setCompanyID(1); aMailing.setId(0); aMailing.setMailTemplateID(templateID); if (aMailing.getMailTemplateID() != 0) { //load Template aMailing = loadTemplate(aMailing, mDao, con); } aMailing.setDescription(description); aMailing.setShortname(shortname); aMailing.setCompanyID(1); if (aMailing.getMailTemplateID() == 0 || mailinglistID != 0) { aMailing.setMailinglistID(mailinglistID); } if (aMailing.getMailTemplateID() == 0 || Integer.valueOf(targetID.getX(0)).intValue() != 0) { Collection targetGroup = new ArrayList(); for (int i = 0; i < targetID.getX().length; i++) { int target = Integer.valueOf(targetID.getX(i)).intValue(); aMailing.setTargetID(target); targetGroup.add(target); } aMailing.setTargetGroups(targetGroup); } if (aMailing.getMailTemplateID() == 0) { aMailing.setMailingType(mailingType); } paramEmail = aMailing.getEmailParam(); if (paramEmail == null) { paramEmail = (MediatypeEmail) con.getBean("MediatypeEmail"); paramEmail.setCompanyID(1); paramEmail.setMailingID(aMailing.getId()); } paramEmail.setStatus(Mediatype.STATUS_ACTIVE); paramEmail.setSubject(emailSubject); try { if (aMailing.getMailTemplateID() == 0 && !emailSender.trim().equalsIgnoreCase("")) { InternetAddress adr = new InternetAddress(emailSender); paramEmail.setFromEmail(adr.getAddress()); paramEmail.setFromFullname(adr.getPersonal()); } } catch (Exception e) { AgnUtils.logger().error("Error in sender address"); } try { if (aMailing.getMailTemplateID() == 0 && !emailReply.trim().equalsIgnoreCase("")) { InternetAddress adr = new InternetAddress(emailReply); paramEmail.setReplyEmail(adr.getAddress()); paramEmail.setReplyFullname(adr.getPersonal()); } } catch (Exception e) { AgnUtils.logger().error("Error in reply address"); } if (aMailing.getMailTemplateID() == 0) { paramEmail.setCharset(emailCharset); paramEmail.setMailFormat(emailFormat); paramEmail.setLinefeed(emailLinefeed); } paramEmail.setPriority(1); paramEmail.setOnepixel(MediatypeEmail.ONEPIXEL_BOTTOM); Map mediatypes = aMailing.getMediatypes(); mediatypes.put(new Integer(0), paramEmail); aMailing.setMediatypes(mediatypes); try { if (aMailing.getMailTemplateID() == 0) { MailingComponent comp = null; comp = (MailingComponent) con.getBean("MailingComponent"); comp.setCompanyID(1); comp.setComponentName("agnText"); comp.setType(MailingComponent.TYPE_TEMPLATE); comp.setEmmBlock("[agnDYN name=\"emailText\"/]"); comp.setMimeType("text/plain"); aMailing.addComponent(comp); comp = (MailingComponent) con.getBean("MailingComponent"); comp.setCompanyID(1); comp.setComponentName("agnHtml"); comp.setType(MailingComponent.TYPE_TEMPLATE); comp.setEmmBlock("[agnDYN name=\"emailHtml\"/]"); comp.setMimeType("text/html"); aMailing.addComponent(comp); } aMailing.buildDependencies(true, con); mDao.saveMailing(aMailing); result = aMailing.getId(); } catch (Exception e) { AgnUtils.logger().info("Error in create mailing id: " + aMailing.getId() + " msg: " + e); result = 0; } return result; }
From source file:edu.stanford.muse.email.AddressBook.java
Contact registerAddress(InternetAddress a) { // get email and name and normalize. email cannot be null, but name can be. String email = a.getAddress(); email = EmailUtils.cleanEmailAddress(email); String name = a.getPersonal(); name = EmailUtils.cleanPersonName(name); if (!Util.nullOrEmpty(name)) { // watch out for bad "names" and ignore them if (name.toLowerCase().equals("'" + email.toLowerCase() + "'")) // sometimes the "name" field is just the same as the email address with quotes around it name = ""; if (name.contains("@")) name = ""; // name can't be an email address! }/*from www . ja va 2s. c om*/ for (String s : DictUtils.bannedStartStringsForEmailAddresses) { if (email.toLowerCase().startsWith(s)) { log.info("not going to consider name-email pair. email: " + email + " name: " + name + " because email starts with " + s); name = ""; // usually something like info@paypal.com or info@evite.com or invitations-noreply@linkedin.com -- we need to ignore the name part of such an email address, so it doesn't get merged with anything else. break; } } List nameTokens = Util.tokenize(name); if (Util.nullOrEmpty(email)) { return null; // we see this happening in the scamletters dataset -- email addr itself is empty! } Contact c = unifyContact(email, name); // DEBUG point: enable this to see all the incoming names and email addrs if (c != null) { if (!c.emails.contains(email)) { if (log.isDebugEnabled()) log.debug("merging email " + email + " into contact " + c); c.emails.add(email); } if (!Util.nullOrEmpty(name) && !c.names.contains(name)) { if (log.isDebugEnabled() && !c.names.contains(name)) log.debug("merging name " + name + " into contact " + c); c.names.add(name); } } // look for names from first.last@... style of email addresses List<String> namesFromEmailAddress = EmailUtils.parsePossibleNamesFromEmailAddress(email); if (log.isDebugEnabled()) { for (String s : namesFromEmailAddress) log.debug("extracted possible name " + s + " from email " + email); } if (namesFromEmailAddress != null) for (String possibleName : namesFromEmailAddress) { if (nameTokens.size() >= 2) unifyContact(email, possibleName); } return c; }
From source file:davmail.imap.ImapConnection.java
protected void appendMailEnvelopeHeader(StringBuilder buffer, String[] value) { buffer.append(' '); if (value != null && value.length > 0) { try {//from w w w .j a v a2 s. 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: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/*w w w . ja v a2s. c om*/ */ 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
/** * /*from w ww. 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: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.//from w w w. j a va 2s. c o m * @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: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 va 2s . co m*/ 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); } }