Example usage for org.apache.commons.mail Email setHostName

List of usage examples for org.apache.commons.mail Email setHostName

Introduction

In this page you can find the example usage for org.apache.commons.mail Email setHostName.

Prototype

public void setHostName(final String aHostName) 

Source Link

Document

Set the hostname of the outgoing mail server.

Usage

From source file:com.doculibre.constellio.wicket.panels.admin.indexing.AdminIndexingPanel.java

private void sendEmail(String hostName, int smtpPort, DefaultAuthenticator authenticator, String sender,
        String subject, String message, String receiver) throws EmailException {
    Email email = new SimpleEmail();
    email.setHostName(hostName);
    email.setSmtpPort(smtpPort);//from ww  w  . j  a v  a  2 s . c om
    email.setAuthenticator(authenticator);
    email.setFrom(sender);
    email.setSubject(subject);
    email.setMsg(message);
    email.addTo(receiver);
    email.send();
}

From source file:com.ms.commons.message.impl.sender.AbstractEmailSender.java

/**
 * Email//from ww  w  . j av a  2 s.  c  om
 * 
 * @param mail
 * @return
 * @throws Exception
 */
protected Email getEmail(MsunMail mail) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("send mail use smth : " + hostName);
    }
    // set env for logger
    mail.getEnvironment().setHostName(hostName);
    mail.getEnvironment().setUser(user);
    mail.getEnvironment().setPassword(password);

    Email email = null;

    if (!StringUtils.isEmpty(mail.getHtmlMessage())) {
        email = makeHtmlEmail(mail, mail.getCharset());
    } else {
        if ((mail.getAttachment() == null || mail.getAttachment().length == 0)
                && mail.getAttachments().isEmpty()) {
            email = makeSimpleEmail(mail, mail.getCharset());
        } else {
            email = makeSimpleEmailWithAttachment(mail, mail.getCharset());
        }
    }

    if (auth) {
        // email.setAuthenticator(new MyAuthenticator(user, password));
        email.setAuthentication(user, password);
    }
    email.setHostName(hostName);

    if (mail.getTo() == null) {
        mail.setTo(defaultTo.split(";"));
    }

    if (StringUtils.isEmpty(mail.getFrom())) {
        mail.setFrom(defaultFrom);
    }

    email.setFrom(mail.getFrom(), mail.getFromName());

    List<String> unqualifiedReceiver = mail.getUnqualifiedReceiver();
    String[] mailTo = mail.getTo();
    String[] mailCc = mail.getCc();
    String[] mailBcc = mail.getBcc();
    if (unqualifiedReceiver != null && unqualifiedReceiver.size() > 0) {
        if (mailTo != null && mailTo.length > 0) {
            mailTo = filterReceiver(mailTo, unqualifiedReceiver);
        }
        if (mailCc != null && mailCc.length > 0) {
            mailCc = filterReceiver(mailCc, unqualifiedReceiver);
        }
        if (mailBcc != null && mailBcc.length > 0) {
            mailBcc = filterReceiver(mailBcc, unqualifiedReceiver);
        }
    }

    if (mailTo == null && mailCc == null && mailBcc == null) {
        throw new MessageSerivceException("?????");
    }

    int count = 0;

    if (mailTo != null) {
        count += mailTo.length;
        for (String to : mailTo) {
            email.addTo(to);
        }
    }

    if (mailCc != null) {
        count += mailCc.length;
        for (String cc : mailCc) {
            email.addCc(cc);
        }
    }
    if (mailBcc != null) {
        count += mailBcc.length;
        for (String bcc : mailBcc) {
            email.addBcc(bcc);
        }
    }

    if (count < 1) {
        throw new MessageSerivceException("?????");
    }

    if (!StringUtils.isEmpty(mail.getReplyTo())) {
        email.addReplyTo(mail.getReplyTo());
    }

    if (mail.getHeaders() != null) {
        for (Iterator<String> iter = mail.getHeaders().keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            email.addHeader(key, (String) mail.getHeaders().get(key));
        }
    }

    email.setSubject(mail.getSubject());

    // 
    if (email instanceof MultiPartEmail) {
        MultiPartEmail multiEmail = (MultiPartEmail) email;

        if (mail.getAttachments().isEmpty()) {
            File[] fs = mail.getAttachment();
            if (fs != null && fs.length > 0) {
                for (int i = 0; i < fs.length; i++) {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(fs[i].getAbsolutePath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setName(MimeUtility.encodeText(fs[i].getName()));// ???
                    multiEmail.attach(attachment);
                }
            }
        } else {
            for (MsunMailAttachment attachment : mail.getAttachments()) {
                DataSource ds = new ByteArrayDataSource(attachment.getData(), null);
                multiEmail.attach(ds, MimeUtility.encodeText(attachment.getName()), null);
            }
        }
    }
    return email;
}

From source file:com.patrolpro.beans.SignupClientBean.java

public String sendEmail() {
    try {//  w  w w  .  j a v  a 2 s.co  m
        boolean isValid = validateInformation();

        if (isValid) {
            StringBuilder emailMessage = new StringBuilder();
            emailMessage.append("Contact Name: " + this.contactName + "\r\n");
            emailMessage.append("Contact Email: " + this.contactEmail + "\r\n");
            emailMessage.append("Contact Phone: " + this.contactPhone + "\r\n");
            emailMessage.append("Company Name: " + this.companyName + "\r\n");
            emailMessage.append(message);

            Email htmlEmail = new SimpleEmail();
            if (message == null || message.length() == 0) {
                message = "No message was provided by the user.";
            }
            htmlEmail.setFrom("signup@patrolpro.com");
            htmlEmail.setSubject("Trial Account Email!");
            htmlEmail.addTo("rharris@ainteractivesolution.com");
            htmlEmail.addTo("ijuneau@ainteractivesolution.com");
            htmlEmail.addCc("jc@champ.net");
            //htmlEmail.setHtmlMsg(emailMessage.toString());
            htmlEmail.setMsg(emailMessage.toString());
            //htmlEmail.setTextMsg(emailMessage.toString());

            htmlEmail.setDebug(true);
            htmlEmail.setAuthenticator(new MailAuthenticator("schedfox", "Sch3dF0x4m3"));
            htmlEmail.setHostName("mail2.champ.net");
            htmlEmail.setSmtpPort(587);
            htmlEmail.send();
            return "sentEmail";
        }
    } catch (Exception exe) {

    }
    return "invalid";
}

From source file:adams.core.net.SimpleApacheSendEmail.java

/**
 * Sends an email./*from   ww w  . ja  va  2s. co m*/
 *
 * @param email   the email to send
 * @return      true if successfully sent
 * @throws Exception   in case of invalid internet addresses or messaging problem
 */
@Override
public boolean sendMail(Email email) throws Exception {
    org.apache.commons.mail.Email mail;
    String id;
    MultiPartEmail mpemail;
    EmailAttachment attachment;

    if (email.getAttachments().length > 0) {
        mail = new MultiPartEmail();
        mpemail = (MultiPartEmail) mail;
        for (File file : email.getAttachments()) {
            attachment = new EmailAttachment();
            attachment.setPath(file.getAbsolutePath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setName(file.getName());
            mpemail.attach(attachment);
        }
    } else {
        mail = new SimpleEmail();
    }
    mail.setFrom(email.getFrom().getValue());
    for (EmailAddress address : email.getTo())
        mail.addTo(address.getValue());
    for (EmailAddress address : email.getCC())
        mail.addCc(address.getValue());
    for (EmailAddress address : email.getBCC())
        mail.addBcc(address.getValue());
    mail.setSubject(email.getSubject());
    mail.setMsg(email.getBody());
    mail.setHostName(m_Server);
    mail.setSmtpPort(m_Port);
    mail.setStartTLSEnabled(m_UseTLS);
    mail.setSSLOnConnect(m_UseSSL);
    if (m_RequiresAuth)
        mail.setAuthentication(m_User, m_Password.getValue());
    mail.setSocketTimeout(m_Timeout);
    try {
        id = mail.send();
        if (isLoggingEnabled())
            getLogger().info("Message sent: " + id);
    } catch (Exception e) {
        getLogger().log(Level.SEVERE, "Failed to send email: " + mail, e);
        return false;
    }

    return true;
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

@Override
public ConnectionTestResponse sendTestEmail(Properties properties) throws Exception {
    String portString = properties.getProperty("port");
    String encryption = properties.getProperty("encryption");
    String host = properties.getProperty("host");
    String timeoutString = properties.getProperty("timeout");
    Boolean authentication = Boolean.parseBoolean(properties.getProperty("authentication"));
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");
    String to = properties.getProperty("toAddress");
    String from = properties.getProperty("fromAddress");

    int port = -1;
    try {/*from  ww  w .  ja  va2 s .co  m*/
        port = Integer.parseInt(portString);
    } catch (NumberFormatException e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                "Invalid port: \"" + portString + "\"");
    }

    Email email = new SimpleEmail();
    email.setDebug(true);
    email.setHostName(host);
    email.setSmtpPort(port);

    try {
        int timeout = Integer.parseInt(timeoutString);
        email.setSocketTimeout(timeout);
        email.setSocketConnectionTimeout(timeout);
    } catch (NumberFormatException e) {
        // Don't set if the value is invalid
    }

    if ("SSL".equalsIgnoreCase(encryption)) {
        email.setSSLOnConnect(true);
        email.setSslSmtpPort(portString);
    } else if ("TLS".equalsIgnoreCase(encryption)) {
        email.setStartTLSEnabled(true);
    }

    if (authentication) {
        email.setAuthentication(username, password);
    }

    // These have to be set after the authenticator, so that a new mail session isn't created
    ConfigurationController configurationController = ControllerFactory.getFactory()
            .createConfigurationController();
    String protocols = properties.getProperty("protocols", StringUtils.join(
            MirthSSLUtil.getEnabledHttpsProtocols(configurationController.getHttpsClientProtocols()), ' '));
    String cipherSuites = properties.getProperty("cipherSuites", StringUtils.join(
            MirthSSLUtil.getEnabledHttpsCipherSuites(configurationController.getHttpsCipherSuites()), ' '));
    email.getMailSession().getProperties().setProperty("mail.smtp.ssl.protocols", protocols);
    email.getMailSession().getProperties().setProperty("mail.smtp.ssl.ciphersuites", cipherSuites);

    SSLSocketFactory socketFactory = (SSLSocketFactory) properties.get("socketFactory");
    if (socketFactory != null) {
        email.getMailSession().getProperties().put("mail.smtp.ssl.socketFactory", socketFactory);
        if ("SSL".equalsIgnoreCase(encryption)) {
            email.getMailSession().getProperties().put("mail.smtp.socketFactory", socketFactory);
        }
    }

    email.setSubject("Mirth Connect Test Email");

    try {
        for (String toAddress : StringUtils.split(to, ",")) {
            email.addTo(toAddress);
        }

        email.setFrom(from);
        email.setMsg(
                "Receipt of this email confirms that mail originating from this Mirth Connect Server is capable of reaching its intended destination.\n\nSMTP Configuration:\n- Host: "
                        + host + "\n- Port: " + port);

        email.send();
        return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS,
                "Sucessfully sent test email to: " + to);
    } catch (EmailException e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, e.getMessage());
    }
}

From source file:easycar.controller.BookingListController.java

public void emailRemind() {
    Email email = new SimpleEmail();
    email.setHostName("smtp.googlemail.com");
    email.setSmtpPort(465);/*from   w w  w .  j  a  va2  s  .c  om*/
    email.setAuthenticator(new DefaultAuthenticator("easycarremind", "easycartest"));
    email.setSSLOnConnect(true);
    try {
        email.setFrom("easycarremind@gmail.com");
        email.setSubject("Reminder to return car");
        email.setMsg("Dear " + selectedBooking.getCustomerName()
                + ",\n\nPlease note that you are supposed to return the car with id "
                + selectedBooking.getCarId() + " to us on " + selectedBooking.getEndDateToDisplay()
                + "\n\nBest regards,\nEasy Car Team.");
        email.addTo(selectedBooking.getCustomerEmail());
        email.send();
    } catch (EmailException e) {
        e.printStackTrace();
    }

    selectedBooking.setLastEmailRemindDate(getZeroTimeDate(new Date()));
    try {
        bookingService.editBooking(selectedBooking);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FacesContext.getCurrentInstance().addMessage("messageDetailDialog", new FacesMessage(
            FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("REMINDER_SENT"), null));
}

From source file:easycar.controller.BookingListController.java

public void emailRemindAll() {
    FullBookingDto currentFullBookingDto;
    for (int i = 0; i < baseFullBookingList.size(); i++) {
        currentFullBookingDto = baseFullBookingList.get(i);

        if (!currentFullBookingDto.isRemindButtonOn()) {
            continue;
        }//  ww  w. ja v  a2  s  . c  o  m

        Email email = new SimpleEmail();
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("easycarremind", "easycartest"));
        email.setSSLOnConnect(true);

        try {
            email.setFrom("easycarremind@gmail.com");
            email.setSubject("Reminder to return car");
            email.setMsg("Dear " + currentFullBookingDto.getCustomerName()
                    + ",\n\nPlease note that you are supposed to return the car with id "
                    + currentFullBookingDto.getCarId() + " to us on "
                    + currentFullBookingDto.getEndDateToDisplay() + "\n\nBest regards,\nEasy Car Team.");
            email.addTo(currentFullBookingDto.getCustomerEmail());
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }

        currentFullBookingDto.setLastEmailRemindDate(getZeroTimeDate(new Date()));
        try {
            bookingService.editBooking(currentFullBookingDto);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    FacesContext.getCurrentInstance().addMessage("messageEmailRemindAll", new FacesMessage(
            FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("REMINDER_SENT"), null));
}

From source file:net.wikiadmin.clientnotification.SendMain.java

/** sendMainText. */
void sendMainText(String cMail, String cName, String cCredit) {

    /* i need your data!!! :D */
    XmlProp readData = new XmlProp("mailsettings.xml");
    readData.readData();/*w  w w.j  a  v a2 s.c  om*/

    userS = readData.getUser();
    passS = readData.getpass();
    hostS = readData.gethost();
    portS = readData.getport();
    sslS = readData.getssl();
    fromS = readData.getfrom();
    toS = cMail;
    intPortS = Integer.parseInt(portS);
    sslBoolean = Boolean.parseBoolean(sslS);
    themeText = readData.getTheme();
    bodyText = readData.getBody() + cName + ".\n" + readData.getBodyP2() + cCredit + readData.getBodyP3() + "\n"
            + readData.getBodyContacts();

    try {
        Email email = new SimpleEmail();
        email.setHostName(hostS);
        email.setAuthenticator(new DefaultAuthenticator(userS, passS));
        email.setSSLOnConnect(sslBoolean);
        email.setSmtpPort(intPortS);
        email.setFrom(fromS);
        email.setSubject(themeText);
        email.setMsg(bodyText);
        email.addTo(toS);
        email.send();
    } catch (EmailException ex) {
        ex.printStackTrace();
        System.out.println("");
    }
}

From source file:org.activiti.engine.impl.bpmn.behavior.MailActivityBehavior.java

protected void setMailServerProperties(Email email) {
    ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();

    String mailSessionJndi = processEngineConfiguration.getMailSesionJndi();
    if (mailSessionJndi != null) {
        try {//w w w. ja  v  a 2 s.c o  m
            email.setMailSessionFromJNDI(mailSessionJndi);
        } catch (NamingException e) {
            throw new ActivitiException("Could not send email: Incorrect JNDI configuration", e);
        }
    } else {
        String host = processEngineConfiguration.getMailServerHost();
        if (host == null) {
            throw new ActivitiException("Could not send email: no SMTP host is configured");
        }
        email.setHostName(host);

        int port = processEngineConfiguration.getMailServerPort();
        email.setSmtpPort(port);

        email.setSSL(processEngineConfiguration.getMailServerUseSSL());
        email.setTLS(processEngineConfiguration.getMailServerUseTLS());

        String user = processEngineConfiguration.getMailServerUsername();
        String password = processEngineConfiguration.getMailServerPassword();
        if (user != null && password != null) {
            email.setAuthentication(user, password);
        }
    }
}

From source file:org.activiti5.engine.impl.bpmn.behavior.MailActivityBehavior.java

protected void setMailServerProperties(Email email, String tenantId) {
    ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();

    boolean isMailServerSet = false;
    if (tenantId != null && tenantId.length() > 0) {
        if (processEngineConfiguration.getMailSessionJndi(tenantId) != null) {
            setEmailSession(email, processEngineConfiguration.getMailSessionJndi(tenantId));
            isMailServerSet = true;/*from   w  ww  .j  a  v a2s.  c om*/

        } else if (processEngineConfiguration.getMailServer(tenantId) != null) {
            MailServerInfo mailServerInfo = processEngineConfiguration.getMailServer(tenantId);
            String host = mailServerInfo.getMailServerHost();
            if (host == null) {
                throw new ActivitiException(
                        "Could not send email: no SMTP host is configured for tenantId " + tenantId);
            }
            email.setHostName(host);

            email.setSmtpPort(mailServerInfo.getMailServerPort());

            email.setSSLOnConnect(processEngineConfiguration.getMailServerUseSSL());
            email.setStartTLSEnabled(processEngineConfiguration.getMailServerUseTLS());

            String user = mailServerInfo.getMailServerUsername();
            String password = mailServerInfo.getMailServerPassword();
            if (user != null && password != null) {
                email.setAuthentication(user, password);
            }

            isMailServerSet = true;
        }
    }

    if (!isMailServerSet) {
        String mailSessionJndi = processEngineConfiguration.getMailSessionJndi();
        if (mailSessionJndi != null) {
            setEmailSession(email, mailSessionJndi);

        } else {
            String host = processEngineConfiguration.getMailServerHost();
            if (host == null) {
                throw new ActivitiException("Could not send email: no SMTP host is configured");
            }
            email.setHostName(host);

            int port = processEngineConfiguration.getMailServerPort();
            email.setSmtpPort(port);

            email.setSSLOnConnect(processEngineConfiguration.getMailServerUseSSL());
            email.setStartTLSEnabled(processEngineConfiguration.getMailServerUseTLS());

            String user = processEngineConfiguration.getMailServerUsername();
            String password = processEngineConfiguration.getMailServerPassword();
            if (user != null && password != null) {
                email.setAuthentication(user, password);
            }
        }
    }
}