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:org.alfresco.email.server.EmailServiceImplTest.java

/**
 * Test the from name.//from   w  w  w. ja v a2s  .  c om
 * 
 * Step 1:
 * User admin will map to the "unknownUser"  which out of the box is "anonymous"
 * Sending email From "admin" will fail. 
 * 
 * Step 2:
 * Send from the test user to the test' user's home folder.
 */
public void testFromName() throws Exception {

    folderEmailMessageHandler.setOverwriteDuplicates(true);

    logger.debug("Start testFromName");

    String TEST_EMAIL = "buffy@sunnydale.high";

    // TODO Investigate why setting PROP_EMAIL on createPerson does not work.
    NodeRef person = personService.getPerson(TEST_USER);
    if (person == null) {
        logger.debug("new person created");
        Map<QName, Serializable> props = new HashMap<QName, Serializable>();
        props.put(ContentModel.PROP_USERNAME, TEST_USER);
        props.put(ContentModel.PROP_EMAIL, TEST_EMAIL);
        person = personService.createPerson(props);
    }
    nodeService.setProperty(person, ContentModel.PROP_EMAIL, TEST_EMAIL);

    Set<String> auths = authorityService.getContainedAuthorities(null, "GROUP_EMAIL_CONTRIBUTORS", true);
    if (!auths.contains(TEST_USER)) {
        authorityService.addAuthority("GROUP_EMAIL_CONTRIBUTORS", TEST_USER);
    }

    String companyHomePathInStore = "/app:company_home";
    String storePath = "workspace://SpacesStore";
    StoreRef storeRef = new StoreRef(storePath);

    NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);
    List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null,
            namespaceService, false);
    NodeRef companyHomeNodeRef = nodeRefs.get(0);
    assertNotNull("company home is null", companyHomeNodeRef);
    String companyHomeDBID = ((Long) nodeService.getProperty(companyHomeNodeRef, ContentModel.PROP_NODE_DBID))
            .toString() + "@Alfresco.com";
    String testUserDBID = ((Long) nodeService.getProperty(person, ContentModel.PROP_NODE_DBID)).toString()
            + "@Alfresco.com";
    NodeRef testUserHomeFolder = (NodeRef) nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER);
    assertNotNull("testUserHomeFolder is null", testUserHomeFolder);
    String testUserHomeDBID = ((Long) nodeService.getProperty(testUserHomeFolder, ContentModel.PROP_NODE_DBID))
            .toString() + "@Alfresco.com";

    /**
     * Step 1
      * Negative test - send from "Bert" who does not exist.
      * User will be mapped to anonymous who is not an email contributor.
      */
    try {
        String from = "admin";
        String to = "bertie";
        String content = "hello world";

        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress("Bert"));
        msg.setRecipients(Message.RecipientType.TO, toa);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);

        EmailDelivery delivery = new EmailDelivery(to, from, null);

        emailService.importMessage(delivery, m);
        fail("anonymous user not rejected");
    } catch (EmailMessageException e) {
        // Check the exception is for the anonymous user.
        assertTrue("Message is not for anonymous", e.getMessage().contains("anonymous"));
    }

    /**
     * Step 2
     * 
     * Send From the test user TEST_EMAIL to the test user's home
     */
    {
        logger.debug("Step 2");

        String from = TEST_EMAIL;
        String to = testUserHomeDBID;
        String content = "hello world";

        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress(TEST_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, toa);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);

        EmailDelivery delivery = new EmailDelivery(to, from, null);

        emailService.importMessage(delivery, m);
    }

    /**
     * Step 3
     * 
     * message.from From with "name" < name@ domain > format
     * SMTP.FROM="dummy"
     * 
     * Send From the test user <TEST_EMAIL> to the test user's home
     */
    {
        logger.debug("Step 3");

        String from = " \"Joe Bloggs\" <" + TEST_EMAIL + ">";
        String to = testUserHomeDBID;
        String content = "hello world";

        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, toa);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(System.out);
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);

        EmailDelivery delivery = new EmailDelivery(to, "dummy", null);

        emailService.importMessage(delivery, m);
    }

    /**
     * Step 4
     * 
     * From with "name" < name@ domain > format
     * 
     * Send From the test user <TEST_EMAIL> to the test user's home
     */
    {
        logger.debug("Step 4");

        String from = " \"Joe Bloggs\" <" + TEST_EMAIL + ">";
        String to = testUserHomeDBID;
        String content = "hello world";

        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, toa);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(System.out);
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);

        InternetAddress a = new InternetAddress(from);
        String x = a.getAddress();

        EmailDelivery delivery = new EmailDelivery(to, x, null);

        emailService.importMessage(delivery, m);
    }

    //       /**
    //        * Step 5
    //        * 
    //        * From with <e=name@domain> format
    //        * 
    //        * RFC3696
    //        * 
    //        * Send From the test user <TEST_EMAIL> to the test user's home
    //        */
    //       {
    //           logger.debug("Step 4 <local tag=name@ domain > format");
    //       
    //           String from = "\"Joe Bloggs\" <e=" + TEST_EMAIL + ">";
    //           String to = testUserHomeDBID;
    //           String content = "hello world";
    //   
    //           Session sess = Session.getDefaultInstance(new Properties());
    //           assertNotNull("sess is null", sess);
    //           SMTPMessage msg = new SMTPMessage(sess);
    //           InternetAddress[] toa =  { new InternetAddress(to) };
    //   
    //           msg.setFrom(new InternetAddress(from));
    //           msg.setRecipients(Message.RecipientType.TO, toa);
    //           msg.setSubject("JavaMail APIs transport.java Test");
    //           msg.setContent(content, "text/plain");
    //           
    //           StringBuffer sb = new StringBuffer();
    //           ByteArrayOutputStream bos = new ByteArrayOutputStream();
    //           msg.writeTo(System.out);
    //           msg.writeTo(bos);
    //           InputStream is = IOUtils.toInputStream(bos.toString());
    //           assertNotNull("is is null", is);
    //   
    //           SubethaEmailMessage m = new SubethaEmailMessage(is);   
    //
    //           emailService.importMessage(m);
    //       }
}

From source file:org.agnitas.web.forms.MailingBaseForm.java

/**
 * Validate the properties that have been set from this HTTP request,
 * and return an <code>ActionErrors</code> object that encapsulates any
 * validation errors that have been found.  If no errors are found, return
 * <code>null</code> or an <code>ActionErrors</code> object with no
 * recorded error messages.//w  w w .j  a v  a2s. c  o  m
 * 
 * @param mapping The mapping used to select this instance
 * @param request The servlet request we are processing
 * @return errors
 */
@Override
public ActionErrors formSpecificValidate(ActionMapping mapping, HttpServletRequest request) {

    ActionErrors errors = new ActionErrors();
    Mailing aMailing = null;

    if (action == MailingBaseAction.ACTION_SAVE) {

        if (this.shortname.length() > 99)
            errors.add("global", new ActionMessage("error.shortname_too_long"));

        if (this.mailinglistID == 0) {
            errors.add("global", new ActionMessage("error.mailing.noMailinglist"));
        }

        if (request.getParameter("addtarget") != null
                && request.getParameter("addtarget").equals("addtarget")) {
            //this.action=MailingBaseAction.ACTION_VIEW_WITHOUT_LOAD;
            if (this.targetID != 0) {
                if (this.targetGroups == null) {
                    this.targetGroups = new HashSet<Integer>();
                }
                this.targetGroups.add(new Integer(this.targetID));
            }
        }

        Enumeration allNames = request.getParameterNames();
        String aName = null;
        int tmpTarget = 0;
        while (allNames.hasMoreElements()) {
            aName = (String) allNames.nextElement();
            if (aName.startsWith("removetarget") && StringUtils.isNotEmpty(request.getParameter(aName))) {
                try {
                    tmpTarget = Integer.parseInt(aName.substring(12));
                } catch (Exception e) {
                    AgnUtils.logger().error("validate: " + e.getMessage());
                }
            }
        }
        if (tmpTarget != 0) {
            this.targetID = tmpTarget;
            this.action = MailingBaseAction.ACTION_REMOVE_TARGET;
        }
    }

    if (action == MailingBaseAction.ACTION_SAVE) {
        if ((this.isIsTemplate() == false) && this.isNeedsTarget() && this.targetGroups == null) {
            errors.add("global", new ActionMessage("error.mailing.rulebased_without_target"));
        }

        if (this.shortname.length() < 3) {
            errors.add("shortname", new ActionMessage("error.nameToShort"));
        }

        // NEW CODE (to be inserted):
        if (this.emailReplytoFullname != null && this.emailReplytoFullname.length() > 255) {
            errors.add("replyFullname", new ActionMessage("error.reply_fullname_too_long"));
        }
        if (getSenderFullname() != null && getSenderFullname().length() > 255) {
            errors.add("senderFullname", new ActionMessage("error.sender_fullname_too_long"));
        }
        if (this.emailReplytoFullname != null && this.emailReplytoFullname.trim().length() == 0) {
            this.emailReplytoFullname = getSenderFullname();
        }

        if (this.targetGroups == null && this.mailingType == Mailing.TYPE_DATEBASED) {
            errors.add("global", new ActionMessage("error.mailing.rulebased_without_target"));
        }

        // NEW CODE (to be inserted):
        if (getMediaEmail().getFromEmail().length() < 3)
            errors.add("shortname", new ActionMessage("error.invalid.email"));

        if (getEmailSubject().length() < 2) {
            errors.add("subject", new ActionMessage("error.mailing.subject.too_short"));
        }

        try {
            InternetAddress adr = new InternetAddress(getMediaEmail().getFromEmail());
            if (adr.getAddress().indexOf("@") == -1) {
                errors.add("sender", new ActionMessage("error.mailing.sender_adress"));
            }
        } catch (Exception e) {
            if (getMediaEmail().getFromEmail().indexOf("[agn") == -1) {
                errors.add("sender", new ActionMessage("error.mailing.sender_adress"));
            }
        }

        try {
            aMailing = (Mailing) getWebApplicationContext().getBean("Mailing");
            aMailing.setCompanyID(this.getCompanyID(request));
            aMailing.findDynTagsInTemplates(this.getEmailSubject(), this.getWebApplicationContext());
            aMailing.findDynTagsInTemplates(this.getSenderFullname(), this.getWebApplicationContext());
        } catch (Exception e) {
            AgnUtils.logger().error("validate: " + e);
            errors.add("subject", new ActionMessage("error.template.dyntags"));
        }

        try {
            aMailing = (Mailing) getWebApplicationContext().getBean("Mailing");
            aMailing.setCompanyID(this.getCompanyID(request));
            aMailing.personalizeText(this.getEmailSubject(), 0, this.getWebApplicationContext());
            aMailing.personalizeText(this.getSenderFullname(), 0, this.getWebApplicationContext());
        } catch (Exception e) {
            errors.add("subject", new ActionMessage("error.personalization_tag"));
        }

        //            if(getTextTemplate().length() != 0) {
        //                // Just a syntax-check, no MailingID required
        //                aMailing = (Mailing) getWebApplicationContext().getBean("Mailing");
        //                aMailing.setCompanyID(this.getCompanyID(request));
        //                
        //                try {
        //                    aMailing.personalizeText(new String(this.getTextTemplate()), 0, this.getWebApplicationContext());
        //                } catch (Exception e) {
        //                    errors.add("texttemplate", new ActionMessage("error.personalization_tag"));
        //                }
        //                
        //                try {
        //                    aMailing.findDynTagsInTemplates(new String(getTextTemplate()), this.getWebApplicationContext());
        //                } catch (Exception e) {
        //                    errors.add("texttemplate", new ActionMessage("error.template.dyntags"));
        //                }
        //                
        //            }
        //            
        //            if(getHtmlTemplate().length() != 0) {
        //                // Just a syntax-check, no MailingID required
        //                aMailing = (Mailing) getWebApplicationContext().getBean("Mailing");
        //                aMailing.setCompanyID(this.getCompanyID(request));
        //                
        //                try {
        //                    aMailing.personalizeText(new String(this.getHtmlTemplate()), 0, this.getWebApplicationContext());
        //                } catch (Exception e) {
        //                    errors.add("texttemplate", new ActionMessage("error.personalization_tag"));
        //                }
        //                
        //                try {
        //                    aMailing.findDynTagsInTemplates(new String(getHtmlTemplate()), this.getWebApplicationContext());
        //                } catch (Exception e) {
        //                    AgnUtils.logger().error("validate: find "+e);
        //                    errors.add("texttemplate", new ActionMessage("error.template.dyntags"));
        //                }
        //            }
    }
    return errors;
}

From source file:org.hyperic.hq.bizapp.server.action.email.EmailAction.java

protected Map<EmailRecipient, AuthzSubject> lookupEmailAddr() throws ActionExecuteException {
    // First, look up the addresses
    HashSet<InternetAddress> prevRecipients = new HashSet<InternetAddress>();
    Map<EmailRecipient, AuthzSubject> validRecipients = new HashMap<EmailRecipient, AuthzSubject>();
    for (Iterator<?> it = getUsers().iterator(); it.hasNext();) {
        try {/* w  ww  .  j  av  a  2 s.c om*/
            InternetAddress addr;
            boolean useHtml = false;
            AuthzSubject who = null;
            switch (getType()) {
            case TYPE_USERS:
                Integer uid = (Integer) it.next();
                who = getSubjMan().getSubjectById(uid);
                if (who == null) {
                    _log.warn("User not found: " + uid);
                    continue;
                }
                addr = (isSms()) ? new InternetAddress(who.getSMSAddress())
                        : new InternetAddress(who.getEmailAddress());
                addr.setPersonal(who.getName());
                useHtml = isSms() ? false : who.isHtmlEmail();
                break;
            default:
            case TYPE_EMAILS:
                addr = new InternetAddress((String) it.next(), true);
                addr.setPersonal(addr.getAddress());
                break;
            }
            // Don't send duplicate notifications
            if (prevRecipients.add(addr)) {
                validRecipients.put(new EmailRecipient(addr, useHtml), who);
            }
        } catch (AddressException e) {
            _log.warn("Mail address invalid", e);
            continue;
        } catch (UnsupportedEncodingException e) {
            _log.warn("Username encoding error", e);
            continue;
        } catch (Exception e) {
            _log.warn("Email lookup failed");
            _log.debug("Email lookup failed", e);
            continue;
        }
    }
    return validRecipients;
}

From source file:net.spfbl.core.Core.java

public static synchronized boolean sendMessage(Message message, int timeout) throws Exception {
    if (message == null) {
        return false;
    } else if (isDirectSMTP()) {
        Server.logInfo("sending e-mail message.");
        Server.logSendMTP("authenticate: false.");
        Server.logSendMTP("start TLS: true.");
        Properties props = System.getProperties();
        props.put("mail.smtp.auth", "false");
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.timeout", Integer.toString(timeout));
        props.put("mail.smtp.connectiontimeout", "3000");
        InternetAddress[] recipients = (InternetAddress[]) message.getAllRecipients();
        Exception lastException = null;
        for (InternetAddress recipient : recipients) {
            String domain = Domain.normalizeHostname(recipient.getAddress(), false);
            for (String mx : Reverse.getMXSet(domain)) {
                mx = mx.substring(1);// ww  w .j  av  a2s. c o m
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", mx);
                props.put("mail.smtp.ssl.trust", mx);
                InternetAddress[] recipientAlone = new InternetAddress[1];
                recipientAlone[0] = (InternetAddress) recipient;
                Session session = Session.getDefaultInstance(props);
                SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
                try {
                    transport.setLocalHost(HOSTNAME);
                    Server.logSendMTP("connecting to " + mx + ":25.");
                    transport.connect(mx, 25, null, null);
                    Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipient + ".");
                    transport.sendMessage(message, recipientAlone);
                    Server.logSendMTP("message '" + message.getSubject() + "' sent to " + recipient + ".");
                    Server.logSendMTP("last response: " + transport.getLastServerResponse());
                    lastException = null;
                    break;
                } catch (MailConnectException ex) {
                    Server.logSendMTP("connection failed.");
                    lastException = ex;
                } catch (SendFailedException ex) {
                    Server.logSendMTP("send failed.");
                    throw ex;
                } catch (MessagingException ex) {
                    if (ex.getMessage().contains(" TLS ")) {
                        Server.logSendMTP("cannot establish TLS connection.");
                        if (transport.isConnected()) {
                            transport.close();
                            Server.logSendMTP("connection closed.");
                        }
                        Server.logInfo("sending e-mail message without TLS.");
                        props.put("mail.smtp.starttls.enable", "false");
                        session = Session.getDefaultInstance(props);
                        transport = (SMTPTransport) session.getTransport("smtp");
                        try {
                            transport.setLocalHost(HOSTNAME);
                            Server.logSendMTP("connecting to " + mx + ":25.");
                            transport.connect(mx, 25, null, null);
                            Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipient + ".");
                            transport.sendMessage(message, recipientAlone);
                            Server.logSendMTP(
                                    "message '" + message.getSubject() + "' sent to " + recipient + ".");
                            Server.logSendMTP("last response: " + transport.getLastServerResponse());
                            lastException = null;
                            break;
                        } catch (SendFailedException ex2) {
                            Server.logSendMTP("send failed.");
                            throw ex2;
                        } catch (Exception ex2) {
                            lastException = ex2;
                        }
                    } else {
                        lastException = ex;
                    }
                } catch (Exception ex) {
                    Server.logError(ex);
                    lastException = ex;
                } finally {
                    if (transport.isConnected()) {
                        transport.close();
                        Server.logSendMTP("connection closed.");
                    }
                }
            }
        }
        if (lastException == null) {
            return true;
        } else {
            throw lastException;
        }
    } else if (hasRelaySMTP()) {
        Server.logInfo("sending e-mail message.");
        Server.logSendMTP("authenticate: " + Boolean.toString(SMTP_IS_AUTH) + ".");
        Server.logSendMTP("start TLS: " + Boolean.toString(SMTP_STARTTLS) + ".");
        Properties props = System.getProperties();
        props.put("mail.smtp.auth", Boolean.toString(SMTP_IS_AUTH));
        props.put("mail.smtp.starttls.enable", Boolean.toString(SMTP_STARTTLS));
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", Short.toString(SMTP_PORT));
        props.put("mail.smtp.timeout", Integer.toString(timeout));
        props.put("mail.smtp.connectiontimeout", "3000");
        props.put("mail.smtp.ssl.trust", SMTP_HOST);
        Address[] recipients = message.getAllRecipients();
        TreeSet<String> recipientSet = new TreeSet<String>();
        for (Address recipient : recipients) {
            recipientSet.add(recipient.toString());
        }
        Session session = Session.getDefaultInstance(props);
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        try {
            if (HOSTNAME != null) {
                transport.setLocalHost(HOSTNAME);
            }
            Server.logSendMTP("connecting to " + SMTP_HOST + ":" + SMTP_PORT + ".");
            transport.connect(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD);
            Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipientSet + ".");
            transport.sendMessage(message, recipients);
            Server.logSendMTP("message '" + message.getSubject() + "' sent to " + recipientSet + ".");
            return true;
        } catch (SendFailedException ex) {
            Server.logSendMTP("send failed.");
            throw ex;
        } catch (AuthenticationFailedException ex) {
            Server.logSendMTP("authentication failed.");
            return false;
        } catch (MailConnectException ex) {
            Server.logSendMTP("connection failed.");
            return false;
        } catch (MessagingException ex) {
            Server.logSendMTP("messaging failed.");
            return false;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        } finally {
            if (transport.isConnected()) {
                transport.close();
                Server.logSendMTP("connection closed.");
            }
        }
    } else {
        return false;
    }
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

private InternetAddress getRawEmailFromAddress(Address address) throws AddressException {
    if (address == null) {
        throw new AddressException("Address cannot be null");
    }/*from   w w  w.j  av  a  2s . com*/
    InternetAddress fromAddress = new InternetAddress(address.toString());
    String fromPlainAddress = fromAddress.getAddress();
    return new InternetAddress(fromPlainAddress);
}

From source file:com.sonicle.webtop.calendar.Service.java

private OUser guessUserByAttendee(CoreManager core, String recipient) {
    Connection con = null;/*from  ww w .  j  ava2 s  .  c  om*/

    try {
        InternetAddress ia = InternetAddressUtils.toInternetAddress(recipient);
        if (ia == null)
            return null;
        List<UserProfileId> pids = core.listUserIdsByEmail(ia.getAddress());
        if (pids.isEmpty())
            return null;
        UserProfileId pid = pids.get(0);

        con = WT.getCoreConnection();
        UserDAO udao = UserDAO.getInstance();
        return udao.selectByDomainUser(con, pid.getDomainId(), pid.getUserId());

    } catch (WTRuntimeException ex) {
        return null;
    } catch (Exception ex) {
        logger.error("Error guessing user from attendee", ex);
        return null;
    } finally {
        DbUtils.closeQuietly(con);
    }
}

From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java

@Override
@Transactional(readOnly = false)/*from w  w  w.  j a  v a2  s  .c  om*/
public boolean sendMessage(@NotNull final Message message)
        throws ObjectNotFoundException, SendFailedException, UnsupportedEncodingException {

    LOGGER.info("BEGIN : sendMessage()");
    LOGGER.info(addMessageIdToError(message) + "Sending message: {}", message.toString());

    try {
        final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        final MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);

        // process FROM addresses
        InternetAddress from;
        String appName = configService.getByName("app_title").getValue();

        //We used the configured outbound email address for every outgoing message
        //If a message was initiated by an end user, their name will be attached to the 'from' while
        //the configured outbound address will be the actual address used for example "Amy Aministrator (SSP) <myconfiguredaddress@foobar.com>"
        String name = appName + " Administrator";
        if (message.getSender() != null && !message.getSender().getEmailAddresses().isEmpty()
                && !message.getSender().getId().equals(Person.SYSTEM_ADMINISTRATOR_ID)) {
            InternetAddress[] froms = getEmailAddresses(message.getSender(), "from:", message.getId());
            if (froms.length > 0) {
                name = message.getSender().getFullName() + " (" + appName + ")";
            }
        }

        from = new InternetAddress(configService.getByName("outbound_email_address").getValue(), name);
        if (!this.validateEmail(from.getAddress())) {
            throw new AddressException("Invalid from: email address [" + from.getAddress() + "]");
        }

        mimeMessageHelper.setFrom(from);
        message.setSentFromAddress(from.toString());
        mimeMessageHelper.setReplyTo(from);
        message.setSentReplyToAddress(from.toString());

        // process TO addresses
        InternetAddress[] tos = null;
        if (message.getRecipient() != null && message.getRecipient().hasEmailAddresses()) { // NOPMD by jon.adams         
            tos = getEmailAddresses(message.getRecipient(), "to:", message.getId());
        } else {
            tos = getEmailAddresses(message.getRecipientEmailAddress(), "to:", message.getId());
        }
        if (tos.length > 0) {
            mimeMessageHelper.setTo(tos);
            message.setSentToAddresses(StringUtils.join(tos, ",").trim());
        } else {
            StringBuilder errorMsg = new StringBuilder();

            errorMsg.append(addMessageIdToError(message) + " Message " + message.toString()
                    + " could not be sent. No valid recipient email address found: '");

            if (message.getRecipient() != null) {
                errorMsg.append(message.getRecipient().getPrimaryEmailAddress());
            } else {
                errorMsg.append(message.getRecipientEmailAddress());
            }
            LOGGER.error(errorMsg.toString());
            throw new MessagingException(errorMsg.toString());
        }

        // process BCC addresses
        try {
            InternetAddress[] bccs = getEmailAddresses(getBcc(), "bcc:", message.getId());
            if (bccs.length > 0) {
                mimeMessageHelper.setBcc(bccs);
                message.setSentBccAddresses(StringUtils.join(bccs, ",").trim());
            }
        } catch (Exception exp) {
            LOGGER.warn("Unrecoverable errors were generated adding carbon copy to message: " + message.getId()
                    + "Attempt to send message still initiated.", exp);
        }

        // process CC addresses
        try {
            InternetAddress[] carbonCopies = getEmailAddresses(message.getCarbonCopy(), "cc:", message.getId());
            if (carbonCopies.length > 0) {
                mimeMessageHelper.setCc(carbonCopies);
                message.setSentCcAddresses(StringUtils.join(carbonCopies, ",").trim());
            }
        } catch (Exception exp) {
            LOGGER.warn("Unrecoverable errors were generated adding bcc to message: " + message.getId()
                    + "Attempt to send message still initiated.", exp);
        }

        mimeMessageHelper.setSubject(message.getSubject());
        mimeMessageHelper.setText(message.getBody());
        mimeMessage.setContent(message.getBody(), "text/html");

        send(mimeMessage);

        message.setSentDate(new Date());
        messageDao.save(message);
    } catch (final MessagingException e) {
        LOGGER.error("ERROR : sendMessage() : {}", e);
        handleSendMessageError(message);
        throw new SendFailedException(addMessageIdToError(message) + "The message parameters were invalid.", e);
    }

    LOGGER.info("END : sendMessage()");
    return true;
}

From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java

@Override
public void send(final MailToSend mail) {
    SmtpConfiguration smtpConfiguration = SmtpConfiguration.fromDefaultSettings();

    MailAddress fromMailAddress = mail.getFrom();
    Session session = getMailSession(smtpConfiguration);
    try {//from w w  w  . j ava2  s .  c  om
        InternetAddress fromAddress = fromMailAddress.getAuthorizedInternetAddress();
        InternetAddress replyToAddress = null;
        List<InternetAddress[]> toAddresses = new ArrayList<>();

        // Parsing destination address for compliance with RFC822.
        final Collection<ReceiverMailAddressSet> addressBatches = mail.getTo().getBatchedReceiversList();
        for (ReceiverMailAddressSet addressBatch : addressBatches) {
            try {
                toAddresses.add(InternetAddress.parse(addressBatch.getEmailsSeparatedByComma(), false));
            } catch (AddressException e) {
                SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE",
                        "From = " + fromMailAddress + ", To = " + addressBatch.getEmailsSeparatedByComma(), e);
            }
        }
        try {
            if (mail.isReplyToRequired()) {
                replyToAddress = new InternetAddress(fromMailAddress.getEmail(), false);
                if (StringUtil.isDefined(fromMailAddress.getName())) {
                    replyToAddress.setPersonal(fromMailAddress.getName(), Charsets.UTF_8.name());
                }
            }
        } catch (AddressException e) {
            SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE",
                    "ReplyTo = " + fromMailAddress + " is malformed.", e);
        }
        MimeMessage email = new MimeMessage(session);
        email.setFrom(fromAddress);
        if (replyToAddress != null) {
            email.setReplyTo(new InternetAddress[] { replyToAddress });
        }
        email.setHeader("Precedence", "list");
        email.setHeader("List-ID", fromAddress.getAddress());
        email.setSentDate(new Date());
        email.setSubject(mail.getSubject(), CharEncoding.UTF_8);
        mail.getContent().applyOn(email);

        // Sending.
        performSend(mail, smtpConfiguration, session, email, toAddresses);

    } catch (MessagingException | UnsupportedEncodingException e) {
        SilverLogger.getLogger(this).error(e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ru.org.linux.user.EditRegisterController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView edit(HttpServletRequest request, HttpServletResponse response,
        @Valid @ModelAttribute("form") EditRegisterRequest form, Errors errors) throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isSessionAuthorized()) {
        throw new AccessViolationException("Not authorized");
    }/*  w  ww .j a  v  a  2s.  c  o m*/

    String nick = tmpl.getNick();
    String password = Strings.emptyToNull(form.getPassword());

    if (password != null && password.equalsIgnoreCase(nick)) {
        errors.reject(null, "   ? ? ");
    }

    InternetAddress mail = null;

    if (!Strings.isNullOrEmpty(form.getEmail())) {
        try {
            mail = new InternetAddress(form.getEmail());
        } catch (AddressException e) {
            errors.rejectValue("email", null, "? e-mail: " + e.getMessage());
        }
    }

    String url = null;

    if (!Strings.isNullOrEmpty(form.getUrl())) {
        url = URLUtil.fixURL(form.getUrl());
    }

    String name = Strings.emptyToNull(form.getName());

    if (name != null) {
        name = StringUtil.escapeHtml(name);
    }

    String town = null;

    if (!Strings.isNullOrEmpty(form.getTown())) {
        town = StringUtil.escapeHtml(form.getTown());
    }

    String info = null;

    if (!Strings.isNullOrEmpty(form.getInfo())) {
        info = StringUtil.escapeHtml(form.getInfo());
    }

    ipBlockDao.checkBlockIP(request.getRemoteAddr(), errors, tmpl.getCurrentUser());

    boolean emailChanged = false;

    User user = userService.getUser(nick);

    if (Strings.isNullOrEmpty(form.getOldpass())) {
        errors.rejectValue("oldpass", null,
                "? ? ?   ");
    } else if (!user.matchPassword(form.getOldpass())) {
        errors.rejectValue("oldpass", null, "? ");
    }

    user.checkAnonymous();

    String newEmail = null;

    if (mail != null) {
        if (user.getEmail() != null && user.getEmail().equals(form.getEmail())) {
            newEmail = null;
        } else {
            if (userDao.getByEmail(mail.getAddress().toLowerCase(), false) != null) {
                errors.rejectValue("email", null, " email  ???");
            }

            newEmail = mail.getAddress().toLowerCase();

            emailChanged = true;
        }
    }

    if (!errors.hasErrors()) {
        userDao.updateUser(user, name, url, newEmail, town, password, info);
        //  token-  ? ? ?
        if (password != null) {
            try {
                UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                        user.getNick(), password);
                UserDetailsImpl details = (UserDetailsImpl) userDetailsService
                        .loadUserByUsername(user.getNick());
                token.setDetails(details);
                Authentication auth = authenticationManager.authenticate(token);
                SecurityContextHolder.getContext().setAuthentication(auth);
                rememberMeServices.loginSuccess(request, response, auth);
            } catch (Exception ex) {
                logger.error(
                        " ? ?    ? ?. ",
                        ex);
            }
        }

        if (emailChanged) {
            emailService.sendEmail(user.getNick(), newEmail, false);
        }
    } else {
        return new ModelAndView("edit-reg");
    }

    if (emailChanged) {
        String msg = " ?  ?. "
                + " ?  " + StringUtil.escapeHtml(newEmail)
                + " ?   ? email.";

        return new ModelAndView("action-done", "message", msg);
    } else {
        return new ModelAndView(new RedirectView("/people/" + tmpl.getNick() + "/profile"));
    }
}