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

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

Introduction

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

Prototype

public Email setFrom(final String email) throws EmailException 

Source Link

Document

Set the FROM field of the email to use the specified address.

Usage

From source file:com.northernwall.hadrian.workItem.email.EmailWorkItemSender.java

private void emailWorkItem(String subject, String body) {
    try {//from ww  w.j  a v a  2s . c o m
        if (emailTos.isEmpty()) {
            return;
        }
        Email email = new SimpleEmail();
        if (smtpHostname != null) {
            email.setHostName(smtpHostname);
        }
        email.setSmtpPort(smtpPort);
        if (smtpUsername != null && smtpPassword != null) {
            email.setAuthenticator(new DefaultAuthenticator(smtpUsername, smtpPassword));
        }
        email.setSSLOnConnect(smtpSsl);
        email.setFrom(emailFrom);
        email.setSubject(subject);
        email.setMsg(body);
        for (String emailTo : emailTos) {
            email.addTo(emailTo);
        }
        email.send();

        if (emailTos.size() == 1) {
            logger.info("Emailing work item to {} with subject {}", emailTos.get(0), subject);
        } else {
            logger.info("Emailing work item to {} and {} other email addresses with subject {}",
                    emailTos.get(0), (emailTos.size() - 1), subject);
        }
    } catch (EmailException ex) {
        throw new RuntimeException("Failure emailing work item, {}", ex);
    }
}

From source file:at.treedb.util.Mail.java

/**
 * /*from   w ww  . ja  v  a 2  s. co m*/
 * @param sendTo
 * @param subject
 * @param message
 * @throws EmailException
 */
public void sendMail(String mailTo, String mailFrom, String subject, String message) throws Exception {
    Objects.requireNonNull(mailTo, "Mail.sendMail(): mailTo can not be null!");
    Objects.requireNonNull(mailFrom, "Mail.sendMail(): mailFrom can not be null!");
    Objects.requireNonNull(subject, "Mail.sendMail(): subject can not be null!");
    Objects.requireNonNull(message, "Mail.sendMail(): message can not be null!");
    Email email = new SimpleEmail();
    email.setHostName(smtpHost);

    email.setAuthenticator(new DefaultAuthenticator(smtpUser, smtpPassword));
    if (transportSecurity == TransportSecurity.SSL) {
        email.setSSLOnConnect(true);
        email.setSSLCheckServerIdentity(false);
    } else if (transportSecurity == TransportSecurity.STARTTLS) {
        email.setStartTLSRequired(true);
    }
    email.setSmtpPort(smtpPort);
    email.setFrom(mailFrom);
    email.setSubject(subject);
    email.setMsg(message);
    email.addTo(mailTo);
    email.send();
}

From source file:FacultyAdvisement.SignupBean.java

public String validateSignUp(ArrayList<Course> list, Appointment appointment)
        throws SQLException, IOException, EmailException {

    if (this.desiredCoureses == null || this.desiredCoureses.size() < 1) {
        FacesContext.getCurrentInstance().addMessage("desiredCourses:Submit",
                new FacesMessage(FacesMessage.SEVERITY_FATAL,
                        "Please select some courses before confirming an appointment.", null));

    }//from   w w  w .  j a va  2s  .c o m
    for (int i = 0; i < list.size(); i++) {
        if (!this.checkRequsites(CourseRepository.readCourseWithRequisites(ds, list.get(i)))) {
            return null;

        }
    }

    try {
        DesiredCourseRepository.deleteFromAppointment(ds, this.appointment.aID);
    } catch (SQLException ex) {
        Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
    }

    DesiredCourseRepository.createDesiredCourses(ds, desiredCoureses, Long.toString(appointment.aID));

    if (!this.edit) {
        try {
            Email email = new HtmlEmail();
            email.setHostName("smtp.googlemail.com");
            email.setSmtpPort(465);
            email.setAuthenticator(new DefaultAuthenticator("uco.faculty.advisement", "!@#$1234"));
            email.setSSLOnConnect(true);
            email.setFrom("uco.faculty.advisement@gmail.com");
            email.setSubject("UCO Faculty Advisement Appointmen Confirmation");

            StringBuilder table = new StringBuilder();
            table.append("<style>" + "td" + "{border-left:1px solid black;" + "border-top:1px solid black;}"
                    + "table" + "{border-right:1px solid black;" + "border-bottom:1px solid black;}"
                    + "</style>");
            table.append(
                    "<table><tr><td  width=\"350\">Course Name</td><td  width=\"350\">Course Subject</td><td  width=\"350\">Course Number</td><td  width=\"350\">Course Credits</td></tr> </table>");
            for (int i = 0; i < this.desiredCoureses.size(); i++) {
                table.append("<tr><td   width=\"350\">" + this.desiredCoureses.get(i).getName() + "</td>"
                        + "<td   width=\"350\">" + this.desiredCoureses.get(i).getSubject() + "</td>"
                        + "<td   width=\"350\">" + this.desiredCoureses.get(i).getNumber() + "</td>"
                        + "<td   width=\"350\">" + this.desiredCoureses.get(i).getCredits() + "</td></tr>"

                );

            }

            email.setMsg("<p>Your appointment with your faculty advisor is at " + appointment.datetime + " on "
                    + appointment.date + " . </p>" + "<p align=\"center\">Desired Courses</p>"
                    + table.toString() + "<p align=\"center\">UCO Faculty Advisement</p></font>"

            );
            email.addTo(username);
            email.send();
        } catch (EmailException ex) {
            Logger.getLogger(VerificationBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return "/customerFolder/profile.xhtml";
}

From source file:Control.CommonsMail.java

/**
 * Classe que envia E-amil//w ww  .  ja  v a 2  s.c  om
 * @throws EmailException
 */
public void enviaEmailSimples(String Msg) throws EmailException {

    Email email = new SimpleEmail();
    email.setDebug(true);
    email.setHostName("smtp.gmail.com"); // o servidor SMTP para envio do e-mail
    //email.setHostName("smtp.pharmapele.com.br"); // o servidor SMTP para envio do e-mail
    email.setSmtpPort(587);
    email.setSSLOnConnect(true);
    email.setStartTLSEnabled(true);
    email.setAuthentication("softwaredeveloperantony@gmail.com", "tony#020567");
    //email.setAuthentication("antony@pharmapele.com.br", "tony#020567");

    //email.setFrom("softwaredeveloperantony@gmail.com"); // remetente
    email.setFrom("antony@pharmapele.com.br"); // remetente
    email.setSubject("Exporta Estoque lojas"); // assunto do e-mail
    email.setMsg(Msg); //conteudo do e-mail
    email.addTo("antony@pharmapele.com.br", "Antony"); //destinatrio

    //email.sets(true);
    //email.setTLS(true);
    try {

        email.send();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.mycollab.servlet.EmailValidationServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String smtpUserName = request.getParameter("smtpUserName");
    String smtpPassword = request.getParameter("smtpPassword");
    String smtpHost = request.getParameter("smtpHost");
    String smtpPort = request.getParameter("smtpPort");
    String tls = request.getParameter("tls");
    String ssl = request.getParameter("ssl");

    int mailServerPort = 25;
    try {//from w ww .  j a  v a 2s.c  o m
        mailServerPort = Integer.parseInt(smtpPort);
    } catch (Exception e) {
        LOG.info("The smtp port value is not a number. We will use default port value is 25");
    }
    try {
        Email email = new SimpleEmail();
        email.setHostName(smtpHost);
        email.setSmtpPort(mailServerPort);
        email.setAuthenticator(new DefaultAuthenticator(smtpUserName, smtpPassword));
        if ("true".equals(tls)) {
            email.setStartTLSEnabled(true);
        } else {
            email.setStartTLSEnabled(false);
        }

        if ("true".equals(ssl)) {
            email.setSSLOnConnect(true);
        } else {
            email.setSSLOnConnect(false);
        }
        email.setFrom(smtpUserName);
        email.setSubject("MyCollab Test Email");
        email.setMsg("This is a test mail ... :-)");
        email.addTo(smtpUserName);
        email.send();
    } catch (EmailException e) {
        PrintWriter out = response.getWriter();
        out.write("Cannot establish SMTP connection. Please recheck your config.");
        LOG.warn("Can not login to SMTP", e);
    }
}

From source file:com.pkrete.locationservice.admin.mailer.impl.BasicEmailService.java

/**
 * Send an email to the given user when the user is created or the password
 * is modified./*www  .  j av a  2  s .com*/
 *
 * @param user the receiver of the email
 */
@Override
public void send(UserFull user) {
    logger.info("Create new email message.");
    Email email = new SimpleEmail();
    email.setHostName(PropertiesUtil.getProperty("mail.host"));
    email.setSmtpPort(this.converterService.strToInt(PropertiesUtil.getProperty("mail.port")));
    email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getProperty("mail.user"),
            PropertiesUtil.getProperty("mail.password")));
    email.setTLS(true);
    try {
        // Init variables
        String header = null;
        String msg = null;

        // Set from address
        email.setFrom(this.messageSource.getMessage("mail.from", null, null));

        // Set message arguments
        Object[] args = new Object[] { user.getUsername(), user.getPasswordUi() };

        // Set variables values
        if (user.getUpdated() == null) {
            // This is a new user
            if (logger.isDebugEnabled()) {
                logger.debug("The message is for a new user.");
            }
            // Set subject
            email.setSubject(this.messageSource.getMessage("mail.title.add", null, null));
            // Set message header
            header = this.messageSource.getMessage("mail.header.add", null, null);
            // Set message content
            msg = this.messageSource.getMessage("mail.message.add", args, null);
        } else {
            // This is an existing user
            logger.debug("The message is for an existing user.");
            // Set subject
            email.setSubject(this.messageSource.getMessage("mail.title.edit", null, null));
            // Get message header
            header = this.messageSource.getMessage("mail.header.edit", null, null);
            // Get message content
            msg = this.messageSource.getMessage("mail.message.edit", args, null);
        }

        // Get note
        String note = this.messageSource.getMessage("mail.note", null, null);
        // Get footer
        String footer = this.messageSource.getMessage("mail.footer", null, null);
        // Get signature
        String signature = this.messageSource.getMessage("mail.signature", null, null);

        // Build message body
        StringBuilder result = new StringBuilder();
        if (!header.isEmpty()) {
            result.append(header).append("\n\n");
        }
        if (!msg.isEmpty()) {
            result.append(msg).append("\n\n");
        }
        if (!note.isEmpty()) {
            result.append(note).append("\n\n");
        }
        if (!footer.isEmpty()) {
            result.append(footer).append("\n\n");
        }
        if (!signature.isEmpty()) {
            result.append(signature).append("\n\n");
        }
        // Set message contents
        email.setMsg(result.toString());
        // Set message receiver
        email.addTo(user.getEmail());
        // Send message
        email.send();
        logger.info("Email was sent to \"{}\".", user.getEmail());
    } catch (Exception e) {
        logger.error("Failed to send email to \"{}\".", user.getEmail());
        logger.error(e.getMessage(), e);
    }
}

From source file:com.irurueta.server.commons.email.ApacheMailSender.java

/**
 * Internal method to send email using Apache Mail.
 * @param m email message.//ww w .  ja v a 2s  . c o  m
 * @param email apache email message.
 * @throws NotSupportedException if feature is not supported.
 * @throws EmailException if Apache Mail cannot send email.
 * @throws com.irurueta.server.commons.email.EmailException if sending
 * email fails.
 */
private void internalSendApacheEmail(EmailMessage m, Email email)
        throws NotSupportedException, EmailException, com.irurueta.server.commons.email.EmailException {
    email.setHostName(mMailHost);
    email.setSmtpPort(mMailPort);
    if (mMailId != null && !mMailId.isEmpty() && mMailPassword != null && !mMailPassword.isEmpty()) {
        email.setAuthenticator(new DefaultAuthenticator(mMailId, mMailPassword));
    }
    email.setStartTLSEnabled(true);
    email.setFrom(mMailFromAddress);
    if (m.getSubject() != null) {
        email.setSubject(m.getSubject());
    }
    m.buildContent(email);

    //add destinatoins
    for (String s : (List<String>) m.getTo()) {
        email.addTo(s);
    }

    for (String s : (List<String>) m.getCC()) {
        email.addCc(s);
    }

    for (String s : (List<String>) m.getBCC()) {
        email.addBcc(s);
    }

    email.send();
}

From source file:com.mirth.connect.connectors.smtp.SmtpSenderService.java

@Override
public Object invoke(String channelId, String method, Object object, String sessionId) throws Exception {
    if (method.equals("sendTestEmail")) {
        SmtpDispatcherProperties props = (SmtpDispatcherProperties) object;

        String host = replacer.replaceValues(props.getSmtpHost(), channelId);
        String portString = replacer.replaceValues(props.getSmtpPort(), channelId);

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

        String secure = props.getEncryption();

        boolean authentication = props.isAuthentication();

        String username = replacer.replaceValues(props.getUsername(), channelId);
        String password = replacer.replaceValues(props.getPassword(), channelId);
        String to = replacer.replaceValues(props.getTo(), channelId);
        String from = replacer.replaceValues(props.getFrom(), channelId);

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

        if ("SSL".equalsIgnoreCase(secure)) {
            email.setSSL(true);
        } else if ("TLS".equalsIgnoreCase(secure)) {
            email.setTLS(true);
        }

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

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

    return null;
}

From source file:com.music.service.EmailService.java

@Async
public void send(EmailDetails details) {
    if (details.getSubject() == null || !BooleanUtils
            .xor(ArrayUtils.toArray(details.getMessage() != null, details.getMessageTemplate() != null))) {
        throw new IllegalStateException(
                "Either subject or subjectKey / either template/message/messageKey should be specified");
    }/*from w ww  .  j a  v a  2s .  c  om*/
    Validate.notBlank(details.getFrom());

    Email email = createEmail(details.isHtml());
    String subject = constructSubject(details);
    email.setSubject(subject);

    String emailMessage = constructEmailMessages(details);

    try {
        if (details.isHtml()) {
            ((HtmlEmail) email).setHtmlMsg(emailMessage);
        } else {
            email.setMsg(emailMessage);
        }

        for (String to : details.getTo()) {
            email.addTo(to);
        }
        email.setFrom(details.getFrom());

        email.send();
    } catch (EmailException ex) {
        logger.error("Exception occurred when sending email to " + details.getTo(), ex);
    }
}

From source file:au.edu.ausstage.utils.EmailManager.java

/**
 * A method for sending a simple email message
 *
 * @param subject the subject of the message
 * @param message the text of the message
 *
 * @return true, if and only if, the email is successfully sent
 *//*from w w w.  ja v  a2  s . com*/
public boolean sendSimpleMessage(String subject, String message) {

    // check the input parameters
    if (InputUtils.isValid(subject) == false || InputUtils.isValid(message) == false) {
        throw new IllegalArgumentException("The subject and message parameters cannot be null");
    }

    try {
        // define helper variables
        Email email = new SimpleEmail();

        // configure the instance of the email class
        email.setSmtpPort(options.getPortAsInt());

        // define authentication if required
        if (InputUtils.isValid(options.getUser()) == true) {
            email.setAuthenticator(new DefaultAuthenticator(options.getUser(), options.getPassword()));
        }

        // turn on / off debugging
        email.setDebug(DEBUG);

        // set the host name
        email.setHostName(options.getHost());

        // set the from email address
        email.setFrom(options.getFromAddress());

        // set the subject
        email.setSubject(subject);

        // set the message
        email.setMsg(message);

        // set the to address
        String[] addresses = options.getToAddress().split(":");

        for (int i = 0; i < addresses.length; i++) {
            email.addTo(addresses[i]);
        }

        // set the security options
        if (options.getTLS() == true) {
            email.setTLS(true);
        }

        if (options.getSSL() == true) {
            email.setSSL(true);
        }

        // send the email
        email.send();

    } catch (EmailException ex) {
        if (DEBUG) {
            System.err.println("ERROR: Sending of email failed.\n" + ex.toString());
        }

        return false;
    }
    return true;
}