Example usage for javax.mail.internet InternetAddress getAddress

List of usage examples for javax.mail.internet InternetAddress getAddress

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress getAddress.

Prototype

public String getAddress() 

Source Link

Document

Get the email address.

Usage

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!// ww  w. j av  a  2  s  .com
 *
 * @param hfactory DOCUMENT ME!
 * @param username DOCUMENT ME!
 * @param mime DOCUMENT ME!
 */
private void parseContacts(Session hsession, Users user, MimeMessage mime, String box) {
    try {
        Address[] addresses = null;

        Date sentDate = null;
        Date receivedDate = null;

        if (box.equals("SENT")) {
            addresses = mime.getAllRecipients();
            sentDate = mime.getSentDate();

            if (sentDate == null) {
                sentDate = new Date();
            }
        } else {
            addresses = mime.getFrom();
            receivedDate = mime.getReceivedDate();

            if (receivedDate == null) {
                receivedDate = new Date();
            }
        }

        if ((addresses != null) && (addresses.length > 0)) {
            String name = null;
            String email = null;

            for (int i = 0; i < addresses.length; i++) {
                if (addresses[i] instanceof InternetAddress) {
                    InternetAddress xinet = (InternetAddress) addresses[i];

                    name = xinet.getPersonal();

                    if ((name != null) && (name.length() > 49)) {
                        name = name.substring(0, 49);
                    }

                    email = xinet.getAddress();
                } else {
                    email = addresses[i].toString();
                }

                Criteria crit1 = hsession.createCriteria(Contact.class);
                crit1.add(Restrictions.eq("users", user));
                crit1.add(Restrictions.eq("conEmail", email));

                Contact contact = (Contact) crit1.uniqueResult();

                if (contact != null) {
                    if (receivedDate != null) {
                        contact.setConReceivedDate(receivedDate);
                    }

                    if (sentDate != null) {
                        contact.setConSentDate(sentDate);
                    }

                    int freq = contact.getConCount();

                    contact.setConCount(freq + 1);

                    if (!StringUtils.isBlank(name)) {
                        name = name.replaceAll(",", " ");
                        name = name.replaceAll(";", " ");
                        contact.setConName(name);
                    }

                    hsession.update(contact);
                } else {
                    contact = new Contact();
                    contact.setConEmail(email);
                    contact.setConName(name);
                    contact.setConReceivedDate(receivedDate);
                    contact.setConSentDate(sentDate);
                    contact.setConCount(new Integer(1));
                    contact.setUsers(user);

                    hsession.save(contact);
                }

                hsession.flush();

                try {
                    if ((contact.getConSentDate() != null) && (contact.getConReceivedDate() != null)) {
                        Criteria crit2 = hsession.createCriteria(Identity.class);
                        crit2.add(Restrictions.eq("ideEmail", email));
                        crit2.add(Restrictions.eq("ideActive", new Boolean(true)));

                        List list = crit2.list();

                        if (list != null) {
                            Iterator scroll = list.iterator();

                            while (scroll.hasNext()) {
                                Identity identity = (Identity) scroll.next();
                                Users buddy = identity.getUsers();

                                if ((buddy != null) && (user.getUseIdint() != buddy.getUseIdint())) {
                                    Criteria auxCrit = hsession.createCriteria(BuddyList.class);
                                    auxCrit.add(Restrictions.eq("usersByBuliOwnerIdint", user));
                                    auxCrit.add(Restrictions.eq("usersByBuliBuddyIdint", buddy));

                                    BuddyList buddyList = (BuddyList) auxCrit.uniqueResult();

                                    if (buddyList != null) {
                                        buddyList.setBuliActive(true);
                                        buddyList.setBuliLastDate(new Date());
                                        hsession.update(buddyList);
                                    } else {
                                        buddyList = new BuddyList();
                                        buddyList.setBuliActive(true);
                                        buddyList.setBuliLastDate(new Date());
                                        buddyList.setUsersByBuliBuddyIdint(buddy);
                                        buddyList.setUsersByBuliOwnerIdint(user);
                                        hsession.save(buddyList);
                                    }
                                }
                            }
                        }

                        hsession.flush();
                    }
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception e) {
    } finally {
    }
}

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 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.//from  w w  w .java2 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:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!/*  www . ja v a  2  s  .c o m*/
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param ideIdint DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_returnPath != null) {
            email.addHeader("Return-Path", _returnPath.getAddress());
            email.addHeader("Errors-To", _returnPath.getAddress());
            email.addHeader("X-Errors-To", _returnPath.getAddress());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

                    File file = new File(dir, obj.getName());

                    bais = new ByteArrayInputStream(obj.getAttachent());
                    fos = new FileOutputStream(file);
                    IOUtils.copy(bais, fos);

                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setDescription("File Attachment: " + file.getName());
                    attachment.setName(file.getName());

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        email.setMailSession(session);

        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();
        int size = MessageUtilities.getMessageSize(mime);

        if (!controlQuota(hsession, user, size)) {
            throw new MailException("ErrorMessages.mail.quota.exceded");
        }

        messageable.storeDraftMessage(getId(), mime, user);
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!/*ww w  .  j  a va 2  s . c o  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:edu.stanford.muse.email.AddressBook.java

public Contact lookupByAddress(Address a) {
    if (a == null || !(a instanceof InternetAddress))
        return null;
    InternetAddress ia = (InternetAddress) a;
    String s = ia.getAddress();
    String s1 = EmailUtils.cleanEmailAddress(s);
    return emailToContact.get(s1);
}

From source file:com.icegreen.greenmail.store.SimpleMessageAttributes.java

/**
 * Parses a String email address to an IMAP address string.
 *//*w ww. j ava 2  s  .  c  om*/
String parseAddress(String address) {
    int comma = address.indexOf(',');
    StringBuilder buf = new StringBuilder();
    if (comma == -1) { //single address
        buf.append(LB);
        InternetAddress netAddr;
        try {
            netAddr = new InternetAddress(address);
        } catch (AddressException ae) {
            return null;
        }
        String personal = netAddr.getPersonal();
        if (personal != null && (personal.length() != 0)) {
            buf.append(Q).append(personal).append(Q);
        } else {
            buf.append(NIL);
        }
        buf.append(SP);
        buf.append(NIL); // should add route-addr
        buf.append(SP);
        try {
            MailAddress mailAddr = new MailAddress(netAddr.getAddress());
            buf.append(Q).append(mailAddr.getUser()).append(Q);
            buf.append(SP);
            buf.append(Q).append(mailAddr.getHost()).append(Q);
        } catch (Exception pe) {
            buf.append(NIL + SP + NIL);
        }
        buf.append(RB);
    } else {
        buf.append(parseAddress(address.substring(0, comma)));
        buf.append(SP);
        buf.append(parseAddress(address.substring(comma + 1)));
    }
    return buf.toString();
}

From source file:edu.stanford.muse.email.AddressBook.java

/**
 * returns true iff a's email address is one of the address book owner's
 *///  w w  w  .  j ava 2 s  .c  o m
boolean isMyAddress(InternetAddress a) {
    if (a == null)
        return false;

    String email = EmailUtils.cleanEmailAddress(a.getAddress());
    Contact selfContact = getContactForSelf();
    if (selfContact == null)
        return false;

    return selfContact.emails.contains(email);
}

From source file:immf.ImodeNetClient.java

/**
 * imode.net????//from   ww  w  .  ja  va 2s . c  o  m
 *
 * @param mail
 * @return
 * @throws IOException
 */
public synchronized void sendMail(SenderMail mail, boolean forcePlaintext) throws IOException, LoginException {
    if (this.logined == null) {
        log.warn("i.net????????");
        this.logined = Boolean.FALSE;
        throw new LoginException("imode.net nologin");
    }
    if (this.logined != null && this.logined == Boolean.FALSE) {
        try {
            this.login();
        } catch (LoginException e) {
            throw new IOException("Could not login to imode.net");
        }
    }
    List<String> inlineFileIdList = new LinkedList<String>();
    List<String> attachmentFileIdList = new LinkedList<String>();
    if (!forcePlaintext) {
        // html?????
        for (SenderAttachment file : mail.getInlineFile()) {
            String docomoFileId = this.sendAttachFile(inlineFileIdList, true,
                    file.getContentTypeWithoutParameter(), file.getFilename(), file.getData());
            file.setDocomoFileId(docomoFileId);
        }
    }
    List<SenderAttachment> attachFiles = mail.getAttachmentFile();
    for (SenderAttachment file : attachFiles) {
        // ?
        this.sendAttachFile(attachmentFileIdList, false, file.getContentTypeWithoutParameter(),
                file.getFilename(), file.getData());
    }

    // html??
    boolean htmlMail = false;
    String body = null;
    if (forcePlaintext) {
        htmlMail = false;
        body = mail.getPlainBody();
    } else {
        body = mail.getHtmlBody(true);
        if (body == null) {
            htmlMail = false;
            body = mail.getPlainBody();
        } else {
            htmlMail = true;
        }
    }

    // html??????cid?
    if (htmlMail) {
        // (???? <img src="40_... ??)
        body = HtmlConvert.replaceAllCaseInsenstive(body, "<img src=\"cid:[^>]*>", "");
    }
    log.info("Html " + htmlMail);
    log.info("body " + body);

    MultipartEntity multi = new MultipartEntity();
    try {
        multi.addPart("folder.id", new StringBody("0", Charset.forName("UTF-8")));
        String mailType = null;
        if (htmlMail) {
            mailType = "1";
        } else {
            mailType = "0";
        }
        multi.addPart("folder.mail.type", new StringBody(mailType, Charset.forName("UTF-8")));

        // ?
        int recipient = 0;
        for (InternetAddress ia : mail.getTo()) {
            multi.addPart("folder.mail.addrinfo(" + recipient + ").mladdr",
                    new StringBody(ia.getAddress(), Charset.forName("UTF-8")));
            multi.addPart("folder.mail.addrinfo(" + recipient + ").type",
                    new StringBody("1", Charset.forName("UTF-8")));
            recipient++;
        }
        for (InternetAddress ia : mail.getCc()) {
            multi.addPart("folder.mail.addrinfo(" + recipient + ").mladdr",
                    new StringBody(ia.getAddress(), Charset.forName("UTF-8")));
            multi.addPart("folder.mail.addrinfo(" + recipient + ").type",
                    new StringBody("2", Charset.forName("UTF-8")));
            recipient++;
        }
        for (InternetAddress ia : mail.getBcc()) {
            multi.addPart("folder.mail.addrinfo(" + recipient + ").mladdr",
                    new StringBody(ia.getAddress(), Charset.forName("UTF-8")));
            multi.addPart("folder.mail.addrinfo(" + recipient + ").type",
                    new StringBody("3", Charset.forName("UTF-8")));
            recipient++;
        }
        if (recipient > 5) {
            throw new IOException("Too Much Recipient");
        }

        // ??
        multi.addPart("folder.mail.subject",
                new StringBody(Util.reverseReplaceUnicodeMapping(mail.getSubject()), Charset.forName("UTF-8")));

        // 
        body = Util.reverseReplaceUnicodeMapping(body);

        // imode.net?? ?10000Bytes?
        if (body.getBytes().length > 10000) {
            // ?byte???????????byte??
            log.warn("????????10000byte");
            throw new IOException("Too Big Message Body. Max 10000 byte.");
        }
        multi.addPart("folder.mail.data", new StringBody(body, Charset.forName("UTF-8")));

        if (!attachmentFileIdList.isEmpty()) {
            // 
            for (int i = 0; i < attachmentFileIdList.size(); i++) {
                multi.addPart("folder.tmpfile(" + i + ").file(0).id",
                        new StringBody(attachmentFileIdList.get(i), Charset.forName("UTF-8")));
            }
        }

        // ??????
        multi.addPart("iemoji(0).id",
                new StringBody(Character.toString((char) 0xe709), Charset.forName("UTF-8"))); // e709 = UTF-8?ee89c9?
        multi.addPart("iemoji(1).id",
                new StringBody(Character.toString((char) 0xe6f0), Charset.forName("UTF-8"))); // e6f0 = UTF-8?ee9bb0?

        multi.addPart("reqtype", new StringBody("0", Charset.forName("UTF-8")));

        HttpPost post = new HttpPost(SendMailUrl);
        try {
            addDumyHeader(post);
            post.setEntity(multi);

            HttpResponse res = this.executeHttp(post);
            if (!isJson(res)) {
                log.warn("?JSON??????");
                if (res != null) {
                    // JSON?????????????????
                    log.debug(toStringBody(res));
                    this.logined = Boolean.FALSE;
                    throw new LoginException("Bad response. no json format.");
                } else {
                    throw new IOException("imode.net not responding. Try later.");
                }
            }
            JSONObject json = JSONObject.fromObject(toStringBody(res));
            String result = json.getJSONObject("common").getString("result");
            if (result.equals("PW1409")) {
                // ????
                this.logined = Boolean.FALSE;
                throw new IOException("PW1409 - session terminated because of your bad mail.");
            } else if (result.equals("PW1430")) {
                // ???
                throw new IOException("PW1430 - User Unknown.");
            } else if (result.equals("PW1436")) {
                // ?????
                JSONArray jsonaddrs = json.getJSONObject("data").getJSONArray("seaddr");
                String addrs = "";
                for (int i = 0; i < jsonaddrs.size(); i++) {
                    if (i > 0) {
                        addrs += ", ";
                    }
                    addrs += jsonaddrs.getString(i);
                }
                throw new IOException("PW1436 - User Unknown.: " + addrs);
            } else if (!result.equals("PW1000")) {
                log.debug(json.toString(2));
                throw new IOException("Bad response " + result);
            }
        } finally {
            post.abort();
            log.info("??");
        }
    } catch (UnsupportedEncodingException e) {
        log.fatal(e);
    }
}

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 w  ww.  j  ava2 s  .  c  o  m*/

    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;
}