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, final String name) throws EmailException 

Source Link

Document

Set the FROM field of the email to use the specified address and the specified personal name.

Usage

From source file:org.apache.wookie.helpers.WidgetKeyManager.java

/**
 * Send email.//from   w ww  .ja v a2s  .  c o  m
 * 
 * @param mailserver - the SMTP mail server address
 * @param from
 * @param to
 * @param message
 * @throws Exception
 */
private static void sendEmail(String mailserver, int port, String from, String to, String message,
        String username, String password) throws EmailException {
    Email email = new SimpleEmail();
    email.setDebug(false); // true if you want to debug
    email.setHostName(mailserver);
    if (username != null) {
        email.setAuthentication(username, password);
        email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
    }
    email.setFrom(from, "Wookie Server");
    email.setSubject("Wookie API Key");
    email.setMsg(message);
    email.addTo(to);
    email.send();
}

From source file:org.cobbzilla.mail.sender.SmtpMailSender.java

@Override
public void send(SimpleEmailMessage message) throws EmailException {

    Email email = constructEmail(message);
    email.setHostName(config.getHost());
    email.setSmtpPort(config.getPort());
    if (config.getHasMailUser()) {
        email.setAuthenticator(new DefaultAuthenticator(config.getUser(), config.getPassword()));
    }/* www .  ja v a 2s .  co m*/
    email.setTLS(config.isTlsEnabled());
    email.setSubject(message.getSubject());
    if (message.getToName() != null) {
        email.addTo(message.getToEmail(), message.getToName());
    } else {
        email.addTo(message.getToEmail());
    }
    if (message.getBcc() != null) {
        email.addBcc(message.getBcc());
    }
    if (message.getCc() != null) {
        email.addCc(message.getCc());
    }
    if (message.getFromName() != null) {
        email.setFrom(message.getFromEmail(), message.getFromName());
    } else {
        email.setFrom(message.getFromEmail());
    }

    sendEmail_internal(email);
}

From source file:org.mifosplatform.billing.message.service.MessageGmailBackedPlatformEmailService.java

@Override
public void sendToUserEmail() {
    Email email = new SimpleEmail();

    String authuserName = "info@hugotechnologies.com";
    //String authusername="hugotechnologies";

    String authuser = "ashokcse556@gmail.com";
    String authpwd = "9989720715";

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(true); // true if you want to debug
    email.setHostName("smtp.gmail.com");
    try {/*from  www  .  ja va  2  s  . c om*/
        email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        email.setFrom(authuserName, authuser);
        List<BillingMessageDataForProcessing> billingMessageDataForProcessings = this.billingMesssageReadPlatformService
                .retrieveMessageDataForProcessing();
        for (BillingMessageDataForProcessing emailDetail : billingMessageDataForProcessings) {

            StringBuilder subjectBuilder = new StringBuilder().append(" ").append(emailDetail.getSubject())
                    .append("  ");

            email.setSubject(subjectBuilder.toString());

            String sendToEmail = emailDetail.getMessageTo();

            StringBuilder messageBuilder = new StringBuilder().append(emailDetail.getHeader()).append(".")
                    .append(emailDetail.getBody()).append(",").append(emailDetail.getFooter());

            email.setMsg(messageBuilder.toString());

            email.addTo(sendToEmail, emailDetail.getMessageFrom());
            email.setSmtpPort(587);
            email.send();
            BillingMessage billingMessage = this.messageDataRepository.findOne(emailDetail.getId());
            if (billingMessage.getStatus().contentEquals("N")) {
                billingMessage.updateStatus();
            }
            this.messageDataRepository.save(billingMessage);

        }
    } catch (EmailException e) {
        throw new MessagePlatformEmailSendException(e);
    }
}

From source file:org.mifosplatform.infrastructure.core.service.GmailBackedPlatformEmailService.java

@Override
public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) {
    final Email email = new SimpleEmail();

    final String authuserName = "support@cloudmicrofinance.com";

    final String authuser = "support@cloudmicrofinance.com";
    final String authpwd = "support80";

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(false); // true if you want to debug
    email.setHostName("smtp.gmail.com");
    try {//from w  w  w  .ja  va 2 s. c  o  m
        email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        email.setFrom(authuser, authuserName);

        final StringBuilder subjectBuilder = new StringBuilder().append("MifosX Prototype Demo: ")
                .append(emailDetail.getContactName()).append(" user account creation.");

        email.setSubject(subjectBuilder.toString());

        final String sendToEmail = emailDetail.getAddress();

        final StringBuilder messageBuilder = new StringBuilder()
                .append("You are receiving this email as your email account: ").append(sendToEmail)
                .append(" has being used to create a user account for an organisation named [")
                .append(emailDetail.getOrganisationName()).append("] on MifosX Prototype Demo.")
                .append("You can login using the following credentials: username: ")
                .append(emailDetail.getUsername()).append(" password: ").append(unencodedPassword);

        email.setMsg(messageBuilder.toString());

        email.addTo(sendToEmail, emailDetail.getContactName());
        email.send();
    } catch (final EmailException e) {
        throw new PlatformEmailSendException(e);
    }
}

From source file:org.mifosplatform.infrastructure.core.service.GmailPlatformEmailService.java

@Override
public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) {
    final Email email = new SimpleEmail();

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(/* w w  w  .j a v a2s  . c o  m*/
            new DefaultAuthenticator(credentials.getAuthUsername(), credentials.getAuthPassword()));
    email.setDebug(false); // true if you want to debug
    email.setHostName("smtp.gmail.com");
    email.setSmtpPort(credentials.getSmtpPort());
    try {
        email.setStartTLSRequired(true);
        email.setStartTLSEnabled(credentials.isStartTls());
        email.setFrom(credentials.getAuthUsername(), credentials.getAuthUsername());

        final StringBuilder subjectBuilder = new StringBuilder().append("FINEM U Ltd.: ")
                .append(emailDetail.getContactName()).append(" user account creation.");

        email.setSubject(subjectBuilder.toString());

        final String sendToEmail = emailDetail.getAddress();

        final StringBuilder messageBuilder = new StringBuilder()
                .append("You are receiving this email as your email account: ").append(sendToEmail)
                .append(" has being used to create a user account for an organisation named [")
                .append(emailDetail.getOrganisationName()).append("].")
                .append("You can login using the following credentials: username: ")
                .append(emailDetail.getUsername()).append(" password: ").append(unencodedPassword);

        email.setMsg(messageBuilder.toString());

        email.addTo(sendToEmail, emailDetail.getContactName());
        email.send();
    } catch (final EmailException e) {
        throw new PlatformEmailSendException(e);
    }
}

From source file:org.mifosplatform.infrastructure.core.service.GmailSendingNotificationToClients.java

public void sendToUserAccount(final String mailAddress, final String approviedDate, final String type,
        final String money) {
    final Email email = new SimpleEmail();
    final String authuserName = "raghuchiluka111@gmail.com";
    final String authuser = "raghuchiluka111@gmail.com";
    final String authpwd = "raghuAkhila";
    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(false); // true if you want to debug
    email.setHostName("smtp.gmail.com");
    email.setSmtpPort(587);//from w w w.j ava 2  s. c  o m
    try {
        email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        email.setFrom(authuser, authuserName);
        final StringBuilder subjectBuilder = new StringBuilder().append(type + ": ");
        email.setSubject(subjectBuilder.toString());
        StringBuilder messageBuilder = null;
        if (money != null)
            messageBuilder = new StringBuilder().append(type + ": ").append(approviedDate)
                    .append("Amount Disbursed:").append(money);
        else
            messageBuilder = new StringBuilder().append(type + ": ").append(approviedDate);
        email.setMsg(messageBuilder.toString());
        email.addTo(mailAddress, mailAddress);
        email.send();
    } catch (final EmailException e) {
        throw new PlatformEmailSendException(e);
    }
}

From source file:org.mifosplatform.infrastructure.security.service.JpaPlatformUserLoginFailureService.java

private void notify(String username, Integer failures) {
    GlobalConfigurationProperty property = globalConfigurationRepository.findOneByName("login-failure-limit");

    Long limit = 3l;//from  w w  w  . j  a v a 2 s. com

    if (property != null && property.isEnabled() && property.getValue() != null) {
        limit = property.getValue();
    }

    // NOTE: only send the email once
    if (failures == limit.intValue()) {
        lock(username);
        try {
            StringBuilder message = new StringBuilder();
            message.append(String.format(template, limit));

            final Email email = new SimpleEmail();
            EmailCredentialsData credentials = getCredentials();
            email.setAuthenticator(
                    new DefaultAuthenticator(credentials.getAuthUsername(), credentials.getAuthPassword()));
            email.setDebug(credentials.isDebug());
            email.setHostName(credentials.getHost());
            email.setSmtpPort(credentials.getSmtpPort());
            email.setStartTLSRequired(true);
            email.setStartTLSEnabled(credentials.isStartTls());
            email.getMailSession().getProperties().put("mail.smtp.auth", true);
            email.setFrom(credentials.getAuthUsername(), credentials.getSenderName());
            email.setSubject(subject);
            email.setMsg(message.toString());
            email.addTo(appUserRepository.getEmailByUsername(username));
            email.send();
        } catch (Exception e) {
            logger.warn(e.toString(), e);
        }

        throw new LockedException(
                "User " + username + " has been locked after " + limit + " failed login attempts.");
    }
}

From source file:org.pepstock.jem.notify.engine.EmailNotifier.java

/**
 * This method sends an <code>Email</code>. <br>
 * It sets in the parameter <code>Email</code> the properties of the
 * parameter <code>JemEmail</code>: From User Email Address, From User Name,
 * subject, text, email destination addresses. <br>
 * It sets in the parameter <code>Email</code> the Email Server property and
 * the optional <code>SMTP</code> port, the properties that indicates if it
 * must use <code>SSL</code> and <code>TLS</code> protocol, the useirid and
 * password for <code>SMTP</code> server authentication if needed, the
 * optional bounce address, the subject, the text, and the recipients of the
 * email.//  w ww.j av  a2s .c om
 * 
 * @param email the <code>JemEmail</code> with the properties of the email
 *            to be sent.
 * @param sendingEmail the real <code>Email</code> that will be sent.
 * @see JemEmail
 * @see Email
 * @throws SendMailException if an error occurs.
 */
private void sendEmail(JemEmail email, Email sendingEmail) throws SendMailException {
    try {
        sendingEmail.setHostName(this.emailServer);
        if (this.smtpPort != NO_SMTP_PORT) {
            sendingEmail.setSmtpPort(this.smtpPort);
        }
        sendingEmail.setFrom(email.getFromUserEmailAddress(), email.getFromUserName());
        if (email.hasSubject()) {
            sendingEmail.setSubject(email.getSubject());
        } else {
            // log no subject
            LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Subject");
        }
        if (email.hasText()) {
            sendingEmail.setMsg(email.getText());
        } else {
            // log no text message
            LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Text Message");
        }
        sendingEmail.setTo(email.getAllToEmailAddresses());
        if (null != this.bounceAddress) {
            sendingEmail.setBounceAddress(this.bounceAddress);
        }
        sendingEmail.setSentDate(new Date());
        sendingEmail.setSSL(this.isSSL);
        sendingEmail.setTLS(this.isTLS);
        if (null != this.authenticationUserId && null != this.authenticationPassword) {
            sendingEmail.setAuthenticator(
                    new DefaultAuthenticator(this.authenticationUserId, this.authenticationPassword));
        }
        sendingEmail.send();
        LogAppl.getInstance().emit(NotifyMessage.JEMN015I, email);
    } catch (EmailException eEx) {
        LogAppl.getInstance().emit(NotifyMessage.JEMN016E, eEx, email);
        throw new SendMailException(NotifyMessage.JEMN016E.toMessage().getFormattedMessage(email), eEx);
    }
}

From source file:org.ploin.pmf.impl.MailSender.java

/**
 *
 * @param email - the email object/*from w  ww  .j a v  a  2s . com*/
 * @param serverConfig - the server config object
 */
private void setServerProperties(Email email, ServerConfig serverConfig) throws MailFactoryException {
    try {
        String host = serverConfig.getHost();
        String fromEmail = serverConfig.getFromEmail();
        String fromName = serverConfig.getFromName();
        String authUser = serverConfig.getAuthUser();
        String authPassword = serverConfig.getAuthPassword();
        String replyTo = serverConfig.getReplyTo();

        email.setHostName(host);
        email.setFrom(fromEmail, fromName);
        if (isNotEmpty(authUser) && isNotEmpty(authPassword))
            email.setAuthentication(authUser, authPassword);

        email.addReplyTo((replyTo != null && !"".equals(replyTo)) ? replyTo : fromEmail);
    } catch (Exception e) {
        throw new MailFactoryException(e);
    }
}

From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java

public void testCommonsEmailOneWaySeparateSessions() {

    Queue emailQueue = null;/*ww w .j  ava  2 s. c  om*/
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    Session clientSession = null;
    Session listenerSession = null;
    // it is not necessary to use the Email interface here
    // Email is used here just to allow for multiple types of emails to
    // occupy
    // the same varaible. SimpleEmail etc can each be used directly.
    List<Email> emails = new ArrayList<Email>();
    EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null,
            null, null, null);
    emails.add(new SimpleEmail(messagingService));
    emails.add(new MultiPartEmail(messagingService));
    emails.add(new HtmlEmail(messagingService));
    try {

        listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = listenerSession.createQueue(emailQueueName);

        consumer = listenerSession.createConsumer(emailQueue);

        consumer.setMessageListener(new EmailListener());

        listenerConn.start();

        listenerSession.run();

    } catch (JMSException e2) {
        e2.printStackTrace();
        Assert.assertTrue(false);
    }

    Wiser smtpServer = new Wiser();
    smtpServer.setPort(smtpTestPort);
    smtpServer.start();

    try {
        clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = clientSession.createQueue(emailQueueName);
        producer = clientSession.createProducer(emailQueue);

        clientConn.start();
        clientSession.run();

    } catch (JMSException e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    }

    for (Email em : emails) {

        try {
            em.addTo(TEST_EMAIL_TO);
            em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL);
            // host and port will be ignored since the email session is
            // established
            // by
            // the listener
            em.setHostName("localhost");
            em.setSmtpPort(smtpTestPort);
            em.setSubject(TEST_EMAIL_SUBJECT);
            if (em instanceof HtmlEmail) {
                em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL);
            } else if (em instanceof MultiPartEmail) {
                em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL);
            } else if (em instanceof SimpleEmail) {
                em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL);
            }

        } catch (EmailException e1) {
            Assert.assertTrue(false);
            e1.printStackTrace();
        }

        try {
            em.buildMimeMessage();
        } catch (EmailException e1) {
            e1.printStackTrace();
            Assert.assertTrue(false);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {

            em.getMimeMessage().writeTo(os);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

        String content = os.toString();

        ObjectMessage om;
        try {
            om = clientSession.createObjectMessage(content);

            om.setJMSType(emailType);

            LOG.info("Client: Sending test message....");
            producer.send(om);
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

    }

    long start = System.currentTimeMillis();
    while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) {
        // wait for transport
    }
    Assert.assertTrue(listenerMessagesProcessed == 3);

    List<WiserMessage> messages = smtpServer.getMessages();
    Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3);

    for (WiserMessage wisermsg : messages) {
        String body = null;
        String subject = null;
        MimeMessage testmail = null;

        try {
            testmail = wisermsg.getMimeMessage();
        } catch (MessagingException e) {
            Assert.assertTrue(false);
            e.printStackTrace();
        }

        if (testmail != null) {
            LOG.info("SMTP server: test email received: ");
            try {
                LOG.info("To: " + testmail.getHeader("To", ","));

                LOG.info("Subject: " + testmail.getHeader("Subject", ","));
                body = getBodyAsString(testmail.getContent());
                subject = testmail.getHeader("Subject", ",");
            } catch (MessagingException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            } catch (IOException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            }
            LOG.info("Body: " + body);
            Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT));
            Assert.assertTrue(body.contains("This is a Commons"));
        } else {
            Assert.assertTrue(false);
        }
    }

    if (clientSession != null) {
        try {
            clientSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        clientSession = null;
    }

    if (listenerSession != null) {
        try {
            listenerSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        listenerSession = null;
    }

    smtpServer.stop();

}