Java Examples for org.apache.commons.mail.Email

The following java examples will help you to understand the usage of org.apache.commons.mail.Email. These source code samples are taken from different open source projects.

Example 1
Project: java-classic-playground-master  File: SendMailController.java View source code
@RequestMapping("/send")
public HttpEntity<Void> send() throws EmailException {
    // An unlucky fool hardcoded some smtp code here.
    Email email = new SimpleEmail();
    email.setHostName("localhost");
    email.setSmtpPort(3025);
    email.setAuthenticator(new DefaultAuthenticator("username", "password"));
    email.setFrom("andreas@kluth.co.uk");
    email.setSubject("TestMail");
    email.setMsg("This is a test mail ... :-)");
    email.addTo("foo@bar.com");
    email.send();
    return ResponseEntity.ok().build();
}
Example 2
Project: gsn-master  File: EmailService.java View source code
/**
     * This method cover most of the cases of sending a simple text email. If the email to be sent has to be configured
     * in a way which is not possible whith the parameters provided (such as html email, or email with attachement, ..),
     * please use the {@link #sendCustomEmail(org.apache.commons.mail.Email)} method and refer the API
     * {@see http://commons.apache.org/email/}.
     *
     * @param to      A set of destination email address of the email. Must contain at least one address.
     * @param object  The subject of the email.
     * @param message The msg of the email.
     * @return true if the email has been sent successfully, false otherwise.
     */
public static boolean sendEmail(ArrayList<String> to, String object, String message) {
    Email email = new SimpleEmail();
    try {
        email.setSubject(object);
        email.setMsg(message);
        if (to != null)
            for (String _to : to) email.addTo(_to);
        sendCustomEmail(email);
        return true;
    } catch (EmailException e) {
        logger.warn("Please, make sure that the SMTP server configuration is correct in the file: " + SMTP_FILE);
        logger.error(e.getMessage(), e);
        return false;
    }
}
Example 3
Project: Mailer-master  File: DefaultAsyncMailerTest.java View source code
@Test
public void should_schedule_mails_to_be_sent_later_and_send_them() throws Exception {
    Email mail = new SimpleEmail();
    Email anotherMail = new SimpleEmail();
    assertFalse(mailer.hasMailToDeliver());
    mailer.sendLater(mail);
    mailer.sendLater(anotherMail);
    assertTrue(mailer.hasMailToDeliver());
    Map<Email, Future<Void>> delivered = mailer.deliverPostponedMails();
    assertThat(delivered.keySet(), containsInAnyOrder(mail, anotherMail));
    verify(mockMailer, times(1)).send(mail);
    verify(mockMailer, times(1)).send(anotherMail);
    assertFalse(mailer.hasMailToDeliver());
    verifyNoMoreInteractions(mockMailer);
}
Example 4
Project: ocr-tools-master  File: Mailer.java View source code
private void send(Email email, String toAddress, String subject, String message) {
    try {
        email.setHostName("localhost");
        email.setFrom("no-reply@gwdg.de");
        email.setSubject(subject);
        email.setMsg(message);
        email.addTo(toAddress);
        email.send();
    } catch (EmailException e) {
        log.error("Could not send mail to " + toAddress, e);
    }
}
Example 5
Project: openiot-master  File: EmailService.java View source code
/**
     * This method cover most of the cases of sending a simple text email. If the email to be sent has to be configured
     * in a way which is not possible whith the parameters provided (such as html email, or email with attachement, ..),
     * please use the {@link #sendCustomEmail(org.apache.commons.mail.Email)} method and refer the API
     * {@see http://commons.apache.org/email/}.
     *
     * @param to      A set of destination email address of the email. Must contain at least one address.
     * @param object  The subject of the email.
     * @param message The msg of the email.
     * @return true if the email has been sent successfully, false otherwise.
     */
public static boolean sendEmail(ArrayList<String> to, String object, String message) {
    Email email = new SimpleEmail();
    try {
        email.setSubject(object);
        email.setMsg(message);
        if (to != null)
            for (String _to : to) email.addTo(_to);
        sendCustomEmail(email);
        return true;
    } catch (EmailException e) {
        logger.warn("Please, make sure that the SMTP server configuration is correct in the file: " + SMTP_FILE);
        logger.error(e.getMessage(), e);
        return false;
    }
}
Example 6
Project: the-job-announcement-fox-master  File: JobAnnouncementServiceImpl.java View source code
// #{jobAnnouncementService.notifyAboutPostings(jobAnnouncementId)}
@Override
public void notifyAboutPostings(Long jobAnnouncementId) {
    JobAnnouncement announcement = find(jobAnnouncementId);
    Email message = new SimpleEmail();
    try {
        message.setSubject("Job Announcement #" + announcement.getId() + " published.");
        User requester = identityService.createUserQuery().userId(announcement.getRequester()).singleResult();
        User editor = identityService.createUserQuery().userId(announcement.getEditor()).singleResult();
        message.addTo("thejobannouncer+" + requester.getId() + "@gmail.com", requester.getFirstName() + " " + requester.getLastName());
        message.addTo("thejobannouncer+" + editor.getId() + "@gmail.com", editor.getFirstName() + " " + editor.getLastName());
        StringBuffer subject = new StringBuffer("News: Your job announcement #[").append(announcement.getId()).append("] has been posted to your Website");
        if (announcement.getTwitterUrl() != null) {
            subject.append(announcement.getFacebookUrl() != null ? ", " : " and ");
            subject.append("Twitter");
        }
        if (announcement.getFacebookUrl() != null)
            subject.append(" and Facebook");
        subject.append("!");
        message.setSubject(subject.toString());
        String nl = System.getProperty("line.separator");
        StringBuffer text = new StringBuffer("Dear ").append(requester.getFirstName()).append(" ").append(requester.getLastName()).append(",").append(nl);
        text.append("dear ").append(editor.getFirstName()).append(" ").append(editor.getLastName()).append(",").append(nl).append(nl);
        text.append("Your job announcement #[").append(announcement.getId()).append("] to search for a '" + announcement.getJobTitle() + "' has just been posted!").append(nl).append(nl);
        text.append("Website: http://the-job-announcement.com/view.jsf?id=" + announcement.getId()).append(nl);
        if (announcement.getTwitterUrl() != null) {
            text.append("Twitter: " + announcement.getTwitterUrl()).append(nl);
        } else if (announcement.getTwitterMessage() != null) {
            text.append("Twitter: Tried, but failed.").append(nl);
        }
        if (announcement.getFacebookUrl() != null) {
            text.append("Facebook: " + announcement.getFacebookUrl()).append(nl);
        } else if (announcement.getFacebookPost() != null) {
            text.append("Facebook: Posting mechanism not yet implemented.").append(nl);
        }
        text.append(nl).append("Have a nice day!").append(nl).append("The Job Announcer ;-)");
        message.setMsg(text.toString());
    /*
             * Disabled actual e-mail sending for the time being due to privacy concerns.
             * We need to make this configurable so people who trying the showcase are aware that
             * an e-mail is being sent and have the possibility of trying this feature themselves.
             */
    // mailingService.post(message);
    } catch (EmailException e) {
        log.warning("Failed to mail Notification with subject '" + message.getSubject() + "'.");
        log.throwing(getClass().getName(), "notifyAboutPostings", e);
        throw new RuntimeException(e);
    }
}
Example 7
Project: Urutau-master  File: EmailManager.java View source code
/**
	 * Sends an email
	 * 
	 * @param subject What refers this email?
	 * @param receiver For whom?
	 * @param message Content of email
	 * 
	 * @throws EmailException case of bad connection
	 */
public void newEmail(String subject, User receiver, String message) throws EmailException {
    Email email = new SimpleEmail();
    email.setSubject(subject);
    email.addTo(receiver.getEmail());
    email.setMsg(message);
    email.setSSLOnConnect(true);
    email.setHostName("smtp.gmail.com");
    email.setSslSmtpPort("465");
    email.setAuthenticator(new DefaultAuthenticator("phwener@gmail.com", "XXX"));
    email.setFrom("phwener@gmail.com");
    email.send();
}
Example 8
Project: find-sec-bugs-master  File: InsecureSmtpSsl.java View source code
public static void main(String[] args) throws Exception {
    Email email = new SimpleEmail();
    email.setHostName("smtp.googlemail.com");
    //OK
    email.setSSLOnConnect(false);
    Email email2 = new SimpleEmail();
    email2.setHostName("smtp2.googlemail.com");
    //BAD
    email2.setSSLOnConnect(true);
    //email2.setSmtpPort(465);
    //email2.setAuthenticator(new DefaultAuthenticator("username", "password"));
    //email2.setFrom("user@gmail.com");
    //email2.setSubject("TestMail");
    //email2.setMsg("This is a test mail ... :-)");
    //email2.addTo("foo@bar.com");
    //email2.send();
    MultiPartEmail emailMulti = new MultiPartEmail();
    emailMulti.setHostName("mail.myserver.com");
    //BAD
    emailMulti.setSSLOnConnect(true);
    HtmlEmail htmlEmail = new HtmlEmail();
    htmlEmail.setHostName("mail.myserver.com");
    //BAD
    htmlEmail.setSSLOnConnect(true);
    ImageHtmlEmail imageEmail = new ImageHtmlEmail();
    imageEmail.setHostName("mail.myserver.com");
    imageEmail.setSSLOnConnect(true);
    //OK
    imageEmail.setSSLCheckServerIdentity(true);
    ImageHtmlEmail imageEmail2 = new ImageHtmlEmail();
    imageEmail2.setHostName("mail2.myserver.com");
    //OK - reversed order
    imageEmail2.setSSLCheckServerIdentity(true);
    imageEmail2.setSSLOnConnect(true);
    ImageHtmlEmail imageEmail3 = new ImageHtmlEmail();
    imageEmail3.setHostName("mail3.myserver.com");
    //BAD
    imageEmail3.setSSLOnConnect(true);
}
Example 9
Project: freezing-octo-bear-master  File: MailServiceTest.java View source code
@Test
public void assertThatNoMatesMailCanBeGeneratedWithUsers() throws UsernameAlreadyTakenException {
    User u1 = userService.createUser("user1", "u", "1", "u1@matetracker.de", "u1");
    User u2 = userService.createUser("user2", "u", "2", "u2@matetracker.de", "u2");
    u1.setMailNotification(true);
    u2.setMailNotification(false);
    userService.persist(u1);
    userService.persist(u2);
    Email mail = mailService.sendNoMatesMail();
    assertThat(mail.getToAddresses().size()).isEqualTo(1);
    userService.deleteUser("user1");
    userService.deleteUser("user2");
}
Example 10
Project: maven-surefire-master  File: BasicTest.java View source code
public void testDependencyFilter() {
    Class testClass = null;
    String testClassName = "org.apache.commons.mail.Email";
    try {
        testClass = Class.forName(testClassName);
        System.out.println("Able to load class " + testClass);
    } catch (ClassNotFoundException e) {
        System.out.println("Couldn't load " + testClassName);
    }
    assertNull(testClass);
}
Example 11
Project: RestComm-master  File: Mail.java View source code
/**
     * Send an email
     */
public static Future<Boolean> send(Email email) {
    try {
        email = buildMessage(email);
        if (Play.configuration.getProperty("mail.smtp", "").equals("mock") && Play.mode == Play.Mode.DEV) {
            Mock.send(email);
            return new Future<Boolean>() {

                public boolean cancel(boolean mayInterruptIfRunning) {
                    return false;
                }

                public boolean isCancelled() {
                    return false;
                }

                public boolean isDone() {
                    return true;
                }

                public Boolean get() throws InterruptedException, ExecutionException {
                    return true;
                }

                public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                    return true;
                }
            };
        }
        email.setMailSession(getSession());
        return sendMessage(email);
    } catch (EmailException ex) {
        throw new MailException("Cannot send email", ex);
    }
}
Example 12
Project: restcommander-master  File: Mail.java View source code
/**
     * Send an email
     */
public static Future<Boolean> send(Email email) {
    try {
        email = buildMessage(email);
        if (Play.configuration.getProperty("mail.smtp", "").equals("mock") && Play.mode == Play.Mode.DEV) {
            Mock.send(email);
            return new Future<Boolean>() {

                public boolean cancel(boolean mayInterruptIfRunning) {
                    return false;
                }

                public boolean isCancelled() {
                    return false;
                }

                public boolean isDone() {
                    return true;
                }

                public Boolean get() throws InterruptedException, ExecutionException {
                    return true;
                }

                public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                    return true;
                }
            };
        }
        email.setMailSession(getSession());
        return sendMessage(email);
    } catch (EmailException ex) {
        throw new MailException("Cannot send email", ex);
    }
}
Example 13
Project: surefire-master  File: BasicTest.java View source code
public void testDependencyFilter() {
    Class testClass = null;
    String testClassName = "org.apache.commons.mail.Email";
    try {
        testClass = Class.forName(testClassName);
        System.out.println("Able to load class " + testClass);
    } catch (ClassNotFoundException e) {
        System.out.println("Couldn't load " + testClassName);
    }
    assertNull(testClass);
}
Example 14
Project: SocialDataImporter-master  File: MailCreatorTest.java View source code
@Test
public void testCreateMailFor() throws Throwable {
    PropertiesPerson person = new PropertiesPerson("person", myPersonProps);
    Email email = myClassUnderTest.createMailFor(person);
    myLog.debug("Created Mail: " + email);
    Assert.assertNotNull(email);
    Assert.assertEquals(THIS_IS_THE_SUBJECT, email.getSubject());
    Object content = Whitebox.getInternalState(email, "content");
    Assert.assertNotNull(content);
    Assert.assertEquals(THIS_IS_THE_BODY, content);
    List<InternetAddress> addresses = email.getToAddresses();
    Assert.assertNotNull(addresses);
    Assert.assertEquals(1, addresses.size());
}
Example 15
Project: Facility-Access-Manager-master  File: EMailLetterAdapter.java View source code
/**
	 * send the email and return an errormessage. if errormessage is empty,
	 * sending succeeded.
	 * 
	 * @param post
	 *            getting the input stream from
	 * @param customid
	 *            for the to send via email
	 * @return an errormessage (may empty on success)
	 */
public String send(PostMethod post, String customid) {
    String errormessage = "";
    if (this.isValid()) {
        File file = null;
        try {
            file = this.getTmpFile(customid);
        } catch (IOException e) {
            FamLog.exception(e, 201106131728l);
            errormessage += "Fail: Create tmp file [201106131729].";
        }
        try {
            InputStream is = post.getResponseBodyAsStream();
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            int bite = 0;
            while ((bite = is.read()) >= 0) {
                bos.write(bite);
            }
            bos.flush();
            bos.close();
        } catch (IOException e) {
            errormessage += "Fail: Write pdf to tmp file [201106141055].";
            FamLog.exception(e, 201106131733l);
        }
        Email mail = this.getEMail(file, this);
        if (mail == null) {
            errormessage += "Fail: Create e-mail object. Please check log files [201106141058].";
        }
        boolean succ = UserMailSender.sendWithoutUserBox(mail);
        if (!succ) {
            errormessage += "Fail: Send email through configured server. Please check log files [201106131756].";
        }
    } else {
        if (this.getTo() == null) {
            errormessage += "Fail: Find an recipient - form email_recipient sent? [201106131757]";
        } else {
            errormessage += "Invalid email address. Recheck email recipient.";
        }
    }
    return errormessage;
}
Example 16
Project: MIFOSX-master  File: GmailBackedPlatformEmailService.java View source code
@Override
public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) {
    final Email email = new SimpleEmail();
    final SMTPCredentialsData smtpCredentialsData = this.externalServicesReadPlatformService.getSMTPCredentials();
    final String authuserName = smtpCredentialsData.getUsername();
    final String authuser = smtpCredentialsData.getUsername();
    final String authpwd = smtpCredentialsData.getPassword();
    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    // true if you want to debug
    email.setDebug(false);
    email.setHostName(smtpCredentialsData.getHost());
    try {
        if (smtpCredentialsData.isUseTLS()) {
            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);
    }
}
Example 17
Project: opencms-core-master  File: CmsNewsletter.java View source code
/**
     * Returns the e-mail for the newsletter.<p>
     * 
     * @param recipient the recipient to whom the newsletter is sent
     * @param cms the CmsObject
     * 
     * @return the e-mail for the newsletter
     * 
     * @throws CmsException if something goes wrong
     */
public Email getEmail(CmsObject cms, I_CmsNewsletterRecipient recipient) throws CmsException {
    StringBuffer htmlMsg = new StringBuffer(1024);
    StringBuffer txtMsg = new StringBuffer(1024);
    Iterator contents = m_contents.iterator();
    while (contents.hasNext()) {
        I_CmsNewsletterContent content = (I_CmsNewsletterContent) contents.next();
        if (recipient.isSubscriber(content)) {
            if (content.getType().equals(CmsNewsletterContentType.TYPE_HTML)) {
                htmlMsg.append(content.getContent());
            } else {
                txtMsg.append(content.getContent());
            }
        }
    }
    Email email = null;
    try {
        if ((htmlMsg.length() > 0) || !m_attachments.isEmpty()) {
            // we need to create a HTML mail
            CmsHtmlMail htmlMail = new CmsHtmlMail();
            htmlMail.setHtmlMsg(replaceMacros(htmlMsg.toString(), recipient));
            Iterator attachments = m_attachments.iterator();
            while (attachments.hasNext()) {
                CmsResource resource = (CmsResource) attachments.next();
                // set the description of the attachment either to the
                // property description, if it is set, or
                // to the property title
                String description = "";
                String propertyDescription = cms.readPropertyObject(cms.getSitePath(resource), CmsPropertyDefinition.PROPERTY_DESCRIPTION, true).getValue();
                if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(propertyDescription)) {
                    description = propertyDescription;
                } else {
                    String propertyTitle = cms.readPropertyObject(cms.getSitePath(resource), CmsPropertyDefinition.PROPERTY_TITLE, true).getValue();
                    description = propertyTitle;
                }
                htmlMail.attach(new CmsVfsDataSource(cms, resource), resource.getName(), description);
            }
            htmlMail.setTextMsg(replaceMacros(txtMsg.toString(), recipient));
            email = htmlMail;
        } else {
            // only text content, return text mail
            CmsSimpleMail textMail = new CmsSimpleMail();
            textMail.setMsg(replaceMacros(txtMsg.toString(), recipient));
            email = textMail;
        }
        email.addTo(recipient.getEmail());
        email.setSubject(m_subject);
    } catch (EmailException e) {
        LOG.error(Messages.get().getBundle().key(Messages.LOG_COMPOSE_MAIL_ERR_0), e);
    }
    return email;
}
Example 18
Project: opencms-master  File: CmsNewsletter.java View source code
/**
     * Returns the e-mail for the newsletter.<p>
     * 
     * @param recipient the recipient to whom the newsletter is sent
     * @param cms the CmsObject
     * 
     * @return the e-mail for the newsletter
     * 
     * @throws CmsException if something goes wrong
     */
public Email getEmail(CmsObject cms, I_CmsNewsletterRecipient recipient) throws CmsException {
    StringBuffer htmlMsg = new StringBuffer(1024);
    StringBuffer txtMsg = new StringBuffer(1024);
    Iterator contents = m_contents.iterator();
    while (contents.hasNext()) {
        I_CmsNewsletterContent content = (I_CmsNewsletterContent) contents.next();
        if (recipient.isSubscriber(content)) {
            if (content.getType().equals(CmsNewsletterContentType.TYPE_HTML)) {
                htmlMsg.append(content.getContent());
            } else {
                txtMsg.append(content.getContent());
            }
        }
    }
    Email email = null;
    try {
        if ((htmlMsg.length() > 0) || !m_attachments.isEmpty()) {
            // we need to create a HTML mail
            CmsHtmlMail htmlMail = new CmsHtmlMail();
            htmlMail.setHtmlMsg(replaceMacros(htmlMsg.toString(), recipient));
            Iterator attachments = m_attachments.iterator();
            while (attachments.hasNext()) {
                CmsResource resource = (CmsResource) attachments.next();
                // set the description of the attachment either to the
                // property description, if it is set, or
                // to the property title
                String description = "";
                String propertyDescription = cms.readPropertyObject(cms.getSitePath(resource), CmsPropertyDefinition.PROPERTY_DESCRIPTION, true).getValue();
                if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(propertyDescription)) {
                    description = propertyDescription;
                } else {
                    String propertyTitle = cms.readPropertyObject(cms.getSitePath(resource), CmsPropertyDefinition.PROPERTY_TITLE, true).getValue();
                    description = propertyTitle;
                }
                htmlMail.attach(new CmsVfsDataSource(cms, resource), resource.getName(), description);
            }
            htmlMail.setTextMsg(replaceMacros(txtMsg.toString(), recipient));
            email = htmlMail;
        } else {
            // only text content, return text mail
            CmsSimpleMail textMail = new CmsSimpleMail();
            textMail.setMsg(replaceMacros(txtMsg.toString(), recipient));
            email = textMail;
        }
        email.addTo(recipient.getEmail());
        email.setSubject(m_subject);
    } catch (EmailException e) {
        LOG.error(Messages.get().getBundle().key(Messages.LOG_COMPOSE_MAIL_ERR_0), e);
    }
    return email;
}
Example 19
Project: yesnotify-master  File: EmailDelivery.java View source code
protected void enableAuthenticator(Email email) {
    if (isSsl()) {
        email.setSSL(true);
    }
    if (isTls()) {
        email.setTLS(true);
    }
    if (StringUtils.isNotBlank(getAuthenticatorUserName()) && StringUtils.isNotBlank(getAuthenticatorPassword())) {
        email.setAuthentication(getAuthenticatorUserName(), getAuthenticatorPassword());
    }
}
Example 20
Project: CISEN-master  File: EmailMessenger.java View source code
@Override
protected void send(EmailConfigDTO configDTO, ToSend message) {
    try {
        Email email = new SimpleEmail();
        email.setHostName(server);
        email.setSmtpPort(port);
        email.setAuthenticator(new DefaultAuthenticator(login, password));
        email.setSSLOnConnect(true);
        email.setFrom(from);
        email.setSubject(message.getSubject());
        email.setMsg(message.getBody());
        email.addTo(configDTO.getRecipient());
        email.send();
    } catch (EmailException ex) {
        LOGGER.error("Send E-mail exception.", ex);
    }
}
Example 21
Project: killbill-master  File: DefaultEmailSender.java View source code
private void sendEmail(final List<String> to, final List<String> cc, final String subject, final Email email) throws EmailApiException {
    try {
        email.setSmtpPort(config.getSmtpPort());
        if (config.useSmtpAuth()) {
            email.setAuthentication(config.getSmtpUserName(), config.getSmtpPassword());
        }
        email.setHostName(config.getSmtpServerName());
        email.setFrom(config.getDefaultFrom());
        email.setSubject(subject);
        if (to != null) {
            for (final String recipient : to) {
                email.addTo(recipient);
            }
        }
        if (cc != null) {
            for (final String recipient : cc) {
                email.addCc(recipient);
            }
        }
        email.setSSL(config.useSSL());
        log.info("Sending email to='{}', cc='{}', subject='{}'", to, cc, subject);
        email.send();
    } catch (EmailException ee) {
        throw new EmailApiException(ee, ErrorCode.EMAIL_SENDING_FAILED);
    }
}
Example 22
Project: Kylin-master  File: MailService.java View source code
/**
     * @param receivers
     * @param subject
     * @param content
     * @return true or false indicating whether the email was delivered successfully
     * @throws IOException
     */
public boolean sendMail(List<String> receivers, String subject, String content, boolean isHtmlMsg) {
    if (!enabled) {
        logger.info("Email service is disabled; this mail will not be delivered: " + subject);
        logger.info("To enable mail service, set 'kylin.job.notification-enabled=true' in kylin.properties");
        return false;
    }
    Email email = new HtmlEmail();
    email.setHostName(host);
    email.setStartTLSEnabled(starttlsEnabled);
    if (starttlsEnabled) {
        email.setSslSmtpPort(port);
    } else {
        email.setSmtpPort(Integer.valueOf(port));
    }
    if (username != null && username.trim().length() > 0) {
        email.setAuthentication(username, password);
    }
    //email.setDebug(true);
    try {
        for (String receiver : receivers) {
            email.addTo(receiver);
        }
        email.setFrom(sender);
        email.setSubject(subject);
        email.setCharset("UTF-8");
        if (isHtmlMsg) {
            ((HtmlEmail) email).setHtmlMsg(content);
        } else {
            ((HtmlEmail) email).setTextMsg(content);
        }
        email.send();
        email.getMailSession();
    } catch (EmailException e) {
        logger.error(e.getLocalizedMessage(), e);
        return false;
    }
    return true;
}
Example 23
Project: nifi-master  File: TestListenSMTP.java View source code
@Override
public void run() {
    for (int i = 0; i < numMessages; i++) {
        try {
            Email email = new SimpleEmail();
            email.setHostName("localhost");
            email.setSmtpPort(port);
            email.setFrom("alice@nifi.apache.org");
            email.setSubject("This is a test");
            email.setMsg("MSG-" + i);
            email.addTo("bob@nifi.apache.org");
            email.send();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            latch.countDown();
        }
    }
}
Example 24
Project: palava-mail-velocity-master  File: EmailFactory.java View source code
/* CHECKSTYLE:OFF */
@SuppressWarnings("unchecked")
Email build(Document document, Embedder embed) throws EmailException, FileNotFoundException {
    /* CHECKSTYLE:ON */
    final Element root = document.getRootElement();
    final List<Element> messages = root.getChildren("message");
    if (messages.isEmpty())
        throw new IllegalArgumentException("No messages found");
    final List<Element> attachments = root.getChildren("attachment");
    final Map<ContentType, String> available = new HashMap<ContentType, String>();
    for (Element element : messages) {
        final String type = element.getAttributeValue("type");
        final ContentType messageType = StringUtils.equals(type, "html") ? ContentType.HTML : ContentType.PLAIN;
        if (available.containsKey(messageType)) {
            throw new IllegalArgumentException("Two messages with the same types have been defined.");
        }
        available.put(messageType, element.getText());
    }
    final Email email;
    if (available.containsKey(ContentType.HTML) || attachments.size() > 0) {
        final HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset(CHARSET);
        if (embed.hasEmbeddings()) {
            htmlEmail.setSubType("related");
        } else if (attachments.size() > 0) {
            htmlEmail.setSubType("related");
        } else {
            htmlEmail.setSubType("alternative");
        }
        /**
             * Add html message
             */
        if (available.containsKey(ContentType.HTML)) {
            htmlEmail.setHtmlMsg(available.get(ContentType.HTML));
        }
        /**
             * Add plain text alternative
             */
        if (available.containsKey(ContentType.PLAIN)) {
            htmlEmail.setTextMsg(available.get(ContentType.PLAIN));
        }
        /**
             * Embedded binary data
             */
        for (Map.Entry<String, String> entry : embed.getEmbeddings().entrySet()) {
            final String path = entry.getKey();
            final String cid = entry.getValue();
            final String name = embed.name(path);
            final File file;
            if (path.startsWith(File.separator)) {
                file = new File(path);
            } else {
                file = new File(embed.getResourcePath(), path);
            }
            if (file.exists()) {
                htmlEmail.embed(new FileDataSource(file), name, cid);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }
        /**
             * Attached binary data
             */
        for (Element attachment : attachments) {
            final String name = attachment.getAttributeValue("name", "");
            final String description = attachment.getAttributeValue("description", "");
            final String path = attachment.getAttributeValue("path");
            if (path == null)
                throw new IllegalArgumentException("Attachment path was not set");
            File file = new File(path);
            if (!file.exists())
                file = new File(embed.getResourcePath(), path);
            if (file.exists()) {
                htmlEmail.attach(new FileDataSource(file), name, description);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }
        email = htmlEmail;
    } else if (available.containsKey(ContentType.PLAIN)) {
        email = new SimpleEmail();
        email.setCharset(CHARSET);
        email.setMsg(available.get(ContentType.PLAIN));
    } else {
        throw new IllegalArgumentException("No valid message found in template.");
    }
    final String subject = root.getChildText("subject");
    email.setSubject(subject);
    final Element from = root.getChild("from");
    final String fromAddress = from == null ? null : from.getText();
    final String fromName = from == null ? fromAddress : from.getAttributeValue("name", fromAddress);
    email.setFrom(fromAddress, fromName);
    final Element to = root.getChild("to");
    if (to != null) {
        final String toAddress = to.getText();
        if (StringUtils.isNotBlank(toAddress) && toAddress.contains(EMAIL_SEPARATOR)) {
            final String[] toAddresses = toAddress.split(EMAIL_SEPARATOR);
            for (String address : toAddresses) {
                email.addTo(address);
            }
        } else if (StringUtils.isNotBlank(toAddress)) {
            final String toName = to.getAttributeValue("name", toAddress);
            email.addTo(toAddress, toName);
        }
    }
    final Element cc = root.getChild("cc");
    if (cc != null) {
        final String ccAddress = cc.getText();
        if (StringUtils.isNotBlank(ccAddress) && ccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] ccAddresses = ccAddress.split(EMAIL_SEPARATOR);
            for (String address : ccAddresses) {
                email.addCc(address);
            }
        } else if (StringUtils.isNotBlank(ccAddress)) {
            final String ccName = cc.getAttributeValue("name", ccAddress);
            email.addCc(ccAddress, ccName);
        }
    }
    final Element bcc = root.getChild("bcc");
    if (bcc != null) {
        final String bccAddress = bcc.getText();
        if (StringUtils.isNotBlank(bccAddress) && bccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] bccAddresses = bccAddress.split(EMAIL_SEPARATOR);
            for (String address : bccAddresses) {
                email.addBcc(address);
            }
        } else if (StringUtils.isNotBlank(bccAddress)) {
            final String bccName = bcc.getAttributeValue("name", bccAddress);
            email.addBcc(bccAddress, bccName);
        }
    }
    final Element replyTo = root.getChild("replyTo");
    if (replyTo != null) {
        final String replyToAddress = replyTo.getText();
        if (StringUtils.isNotBlank(replyToAddress) && replyToAddress.contains(EMAIL_SEPARATOR)) {
            final String[] replyToAddresses = replyToAddress.split(EMAIL_SEPARATOR);
            for (String address : replyToAddresses) {
                email.addReplyTo(address);
            }
        } else if (StringUtils.isNotBlank(replyToAddress)) {
            final String replyToName = replyTo.getAttributeValue("name", replyToAddress);
            email.addReplyTo(replyToAddress, replyToName);
        }
    }
    return email;
}
Example 25
Project: Repository-master  File: EmailManagerImpl.java View source code
//
// Mail sending
//
/**
   * Apply server configuration to email.
   */
@VisibleForTesting
Email apply(final EmailConfiguration configuration, final Email mail) throws EmailException {
    mail.setHostName(configuration.getHost());
    mail.setSmtpPort(configuration.getPort());
    if (!Strings.isNullOrEmpty(configuration.getUsername()) || !Strings.isNullOrEmpty(configuration.getPassword())) {
        mail.setAuthentication(configuration.getUsername(), configuration.getPassword());
    }
    mail.setStartTLSEnabled(configuration.isStartTlsEnabled());
    mail.setStartTLSRequired(configuration.isStartTlsRequired());
    mail.setSSLOnConnect(configuration.isSslOnConnectEnabled());
    mail.setSSLCheckServerIdentity(configuration.isSslCheckServerIdentityEnabled());
    mail.setSslSmtpPort(Integer.toString(configuration.getPort()));
    // default from address
    if (mail.getFromAddress() == null) {
        mail.setFrom(configuration.getFromAddress());
    }
    // apply subject prefix if configured
    String subjectPrefix = configuration.getSubjectPrefix();
    if (subjectPrefix != null) {
        String subject = mail.getSubject();
        mail.setSubject(String.format("%s %s", subjectPrefix, subject));
    }
    // do this last (mail properties are set up from the email fields when you get the mail session)
    if (configuration.isNexusTrustStoreEnabled()) {
        SSLContext context = trustStore.getSSLContext();
        Session session = mail.getMailSession();
        Properties properties = session.getProperties();
        properties.remove(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_CLASS);
        properties.put(EmailConstants.MAIL_SMTP_SSL_ENABLE, true);
        properties.put("mail.smtp.ssl.socketFactory", context.getSocketFactory());
    }
    return mail;
}
Example 26
Project: speakeasy-plugin-master  File: RefappProductAccessor.java View source code
public void sendEmail(EmailOptions options) {
    String toName = options.getToName();
    String toEmail = options.getToEmail();
    if (options.getToUsername() != null) {
        UserProfile to = userManager.getUserProfile(options.getToUsername());
        if (to != null) {
            toName = to.getFullName();
            toEmail = to.getEmail();
        } else {
            log.warn("Cannot find profile for user '" + options.getToUsername());
            return;
        }
    }
    Map<String, Object> context = newHashMap(options.getContext());
    context.put("toFullName", toName);
    Email email = new SimpleEmail();
    try {
        email.setHostName("localhost");
        email.setSmtpPort(2525);
        email.setFrom(options.getFromEmail(), options.getFromName());
        email.setSubject("[test] " + render(options.getSubjectTemplate(), context));
        email.setMsg(render(options.getBodyTemplate(), context));
        email.addTo(toEmail);
        if (options.getReplyToEmail() != null) {
            email.setReplyTo(Arrays.asList(new InternetAddress(options.getReplyToEmail())));
        }
        email.send();
    } catch (EmailException e) {
        log.error("Unable to send email", e);
        if (log.isDebugEnabled()) {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            try {
                email.getMimeMessage().writeTo(bout);
                log.debug("Sent email:\n" + new String(bout.toByteArray()));
            } catch (MessagingException ex) {
                throw new RuntimeException(ex);
            } catch (IOException e1) {
                throw new RuntimeException(e1);
            }
        }
    } catch (IOException e) {
        log.error("Unable to send email", e);
    } catch (AddressException e) {
        log.error("Invalid reply to address: " + options.getReplyToEmail(), e);
    }
}
Example 27
Project: vraptor-mauth-master  File: PasswordForgotControllerSpec.java View source code
private Matcher<? extends Email> emailTo(final String name, final String email) {
    return new TypeSafeMatcher<Email>() {

        @Override
        public void describeTo(Description desc) {
            desc.appendText("Email to " + name + " <" + email + ">");
        }

        @Override
        public boolean matchesSafely(Email sent) {
            try {
                return sent.getToAddresses().contains(new InternetAddress(email, name));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    };
}
Example 28
Project: DataHubSystem-master  File: MailServer.java View source code
public void send(Email email, String to, String cc, String bcc, String subject) throws EmailException {
    email.setHostName(getSmtpServer());
    email.setSmtpPort(getPort());
    if ((getUsername() != null) && !getUsername().isEmpty()) {
        email.setAuthentication(getUsername(), getPassword());
    }
    if (getFromMail() != null) {
        if (getFromName() != null)
            email.setFrom(getFromMail(), getFromName());
        else
            email.setFrom(getFromMail());
    }
    if (getReplyto() != null) {
        try {
            email.setReplyTo(ImmutableList.of(new InternetAddress(getReplyto())));
        } catch (AddressException e) {
            LOGGER.error("Cannot configure Reply-to (" + getReplyto() + ") into the mail: " + e.getMessage());
        }
    }
    // Message configuration
    email.setSubject("[" + cfgManager.getNameConfiguration().getShortName() + "] " + subject);
    email.addTo(to);
    // Add CCed
    if (cc != null) {
        email.addCc(cc);
    }
    // Add BCCed
    if (bcc != null) {
        email.addBcc(bcc);
    }
    email.setStartTLSEnabled(isTls());
    try {
        email.send();
    } catch (EmailException e) {
        LOGGER.error("Cannot send email: " + e.getMessage());
        throw e;
    }
}
Example 29
Project: fa15-ceg3120-master  File: EmailManager.java View source code
/**
	 * Add an outgoing email to the queue.
	 * @param to Array of email addresses.
	 * @param subject Header
	 * @param body Content
	 * @param attachmentFile Attachment
	 */
public void addEmail(String[] to, String subject, String body, File attachmentFile) {
    HtmlEmail mail = new HtmlEmail();
    Properties sysProps = System.getProperties();
    // Setup mail server
    sysProps.setProperty("mail.smtp.host", props.getProperty("mail_server_hostname"));
    Session session = Session.getDefaultInstance(sysProps);
    try {
        mail.setMailSession(session);
        mail.setFrom(props.getProperty("server_email_addr"), props.getProperty("server_title"));
        mail.addTo(to);
        mail.setSubject(subject);
        mail.setTextMsg(body);
        mail.setHtmlMsg(composeAsHtml(mail, body));
        if (attachmentFile.exists()) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(attachmentFile.getPath());
            mail.attach(attachment);
        }
    } catch (EmailException e) {
        LOG.warn("Email was not added. ", e);
    }
    mailQueue.add(mail);
}
Example 30
Project: gobblin-master  File: EmailUtils.java View source code
/**
   * A general method for sending emails.
   *
   * @param state a {@link State} object containing configuration properties
   * @param subject email subject
   * @param message email message
   * @throws EmailException if there is anything wrong sending the email
   */
public static void sendEmail(State state, String subject, String message) throws EmailException {
    Email email = new SimpleEmail();
    email.setHostName(state.getProp(ConfigurationKeys.EMAIL_HOST_KEY, ConfigurationKeys.DEFAULT_EMAIL_HOST));
    if (state.contains(ConfigurationKeys.EMAIL_SMTP_PORT_KEY)) {
        email.setSmtpPort(state.getPropAsInt(ConfigurationKeys.EMAIL_SMTP_PORT_KEY));
    }
    email.setFrom(state.getProp(ConfigurationKeys.EMAIL_FROM_KEY));
    if (state.contains(ConfigurationKeys.EMAIL_USER_KEY) && state.contains(ConfigurationKeys.EMAIL_PASSWORD_KEY)) {
        email.setAuthentication(state.getProp(ConfigurationKeys.EMAIL_USER_KEY), PasswordManager.getInstance(state).readPassword(state.getProp(ConfigurationKeys.EMAIL_PASSWORD_KEY)));
    }
    Iterable<String> tos = Splitter.on(',').trimResults().omitEmptyStrings().split(state.getProp(ConfigurationKeys.EMAIL_TOS_KEY));
    for (String to : tos) {
        email.addTo(to);
    }
    String hostName;
    try {
        hostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException uhe) {
        LOGGER.error("Failed to get the host name", uhe);
        hostName = "unknown";
    }
    email.setSubject(subject);
    String fromHostLine = String.format("This email was sent from host: %s%n%n", hostName);
    email.setMsg(fromHostLine + message);
    email.send();
}
Example 31
Project: ipdburt-master  File: MailManager.java View source code
private void setEmailProps(Email email) throws EmailException {
    email.setFrom(props.getProperty("from"), "IPDB");
    if (props.containsKey("bounce"))
        email.setBounceAddress(props.getProperty("bounce"));
    if (props.containsKey("host"))
        email.setHostName(props.getProperty("host"));
    if (props.containsKey("port"))
        email.setSmtpPort(Integer.parseInt(props.getProperty("port")));
    if (props.containsKey("username"))
        email.setAuthenticator(new DefaultAuthenticator(props.getProperty("username"), props.getProperty("password")));
    if (props.containsKey("ssl") && props.getProperty("ssl").equalsIgnoreCase("true"))
        email.setSSL(true);
    if (props.containsKey("tls") && props.getProperty("tls").equalsIgnoreCase("true"))
        email.setTLS(true);
    if (props.containsKey("debug") && props.getProperty("debug").equalsIgnoreCase("true"))
        email.setDebug(true);
}
Example 32
Project: Japid-master  File: JapidMailer.java View source code
@SuppressWarnings("unchecked")
public static Future<Boolean> send(Object... args) {
    try {
        final HashMap<String, Object> infoMap = getInfoMap();
        // Body character set
        final String charset = (String) infoMap.get(CHARSET);
        // Headers
        final Map<String, String> headers = (Map<String, String>) infoMap.get(HEADERS);
        // Subject
        final String subject = (String) infoMap.get(SUBJECT);
        // xxx how to determine the method name???
        //            String templateName = (String) infoMap.get(METHOD);
        String templateNameBase = StackTraceUtils.getCaller();
        if (!templateNameBase.startsWith("notifiers")) {
            throw new RuntimeException("The emailers must be put in the \"notifiers\" package.");
        }
        //            if (templateNameBase.startsWith(NOTIFIERS)) {
        //                templateNameBase = templateNameBase.substring(NOTIFIERS.length());
        //            }
        //            if (templateNameBase.startsWith(CONTROLLERS)) {
        //                templateNameBase = templateNameBase.substring(CONTROLLERS.length());
        //            }
        //            templateNameBase = templateNameBase.substring(0, templateNameBase.indexOf("("));
        //            templateNameBase = templateNameBase.replace(".", "/");
        //            final Map<String, Object> templateHtmlBinding = new HashMap<String, Object>();
        //            final Map<String, Object> templateTextBinding = new HashMap<String, Object>();
        //            for (Object o : args) {
        //                List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o);
        //                for (String name : names) {
        //                    templateHtmlBinding.put(name, o);
        //                    templateTextBinding.put(name, o);
        //                }
        //            }
        String templateClassName = DirUtil.JAPIDVIEWS_ROOT + "._" + templateNameBase;
        String bodyHtml = null;
        Class tClass = Play.classloader.getClassIgnoreCase(templateClassName);
        if (tClass == null) {
            String templateFileName = templateClassName.replace('.', '/') + ".html";
            throw new RuntimeException("Japid Emailer: could not find a Japid template with the name of: " + templateFileName);
        } else if (JapidTemplateBase.class.isAssignableFrom(tClass)) {
            try {
                JapidController.render(tClass, args);
            } catch (JapidResult jr) {
                RenderResult rr = jr.getRenderResult();
                bodyHtml = rr.getContent().toString();
            }
        } else {
            throw new RuntimeException("The found class is not a Japid template class: " + templateClassName);
        }
        //    		System.out.println("email body: " + bodyHtml);
        // The rule is as follow: If we ask for text/plain, we don't care about the HTML
        // If we ask for HTML and there is a text/plain we add it as an alternative.
        // If contentType is not specified look at the template available:
        // - .txt only -> text/plain
        // else
        // -           -> text/html
        //            String contentType = (String) infoMap.get(CONTENT_TYPE);
        //            String bodyText = "";
        //            try {
        //                Template templateHtml = TemplateLoader.load(templateNameBase + ".html");
        //                bodyHtml = templateHtml.render(templateHtmlBinding);
        //            } catch (TemplateNotFoundException e) {
        //                if (contentType != null && !contentType.startsWith(TEXT_PLAIN)) {
        //                    throw e;
        //                }
        //            }
        ////
        //            try {
        //                Template templateText = TemplateLoader.load(templateName + ".txt");
        //                bodyText = templateText.render(templateTextBinding);
        //            } catch (TemplateNotFoundException e) {
        //                if (bodyHtml == null && (contentType == null || contentType.startsWith(TEXT_PLAIN))) {
        //                    throw e;
        //                }
        //            }
        // Content type
        // bran html for now
        //            if (contentType == null) {
        //                if (bodyHtml != null) {
        //                    contentType = TEXT_HTML;
        //                } else {
        //                    contentType = TEXT_PLAIN;
        //                }
        //            }
        // Recipients
        final List<Object> recipientList = (List<Object>) infoMap.get(RECIPIENTS);
        // From
        final Object from = infoMap.get(FROM);
        final Object replyTo = infoMap.get(REPLY_TO);
        Email email = null;
        if (infoMap.get(ATTACHMENTS) == null) {
            //                if (StringUtils.isEmpty(bodyHtml)) {
            //                    email = new SimpleEmail();
            //                    email.setMsg(bodyText);
            //                } else {
            HtmlEmail htmlEmail = new HtmlEmail();
            htmlEmail.setHtmlMsg(bodyHtml);
            //                    if (!StringUtils.isEmpty(bodyText)) {
            //                        htmlEmail.setTextMsg(bodyText);
            //                    }
            email = htmlEmail;
        //                }
        } else {
            //                if (StringUtils.isEmpty(bodyHtml)) {
            //                    email = new MultiPartEmail();
            //                    email.setMsg(bodyText);
            //                } else {
            HtmlEmail htmlEmail = new HtmlEmail();
            htmlEmail.setHtmlMsg(bodyHtml);
            //                    if (!StringUtils.isEmpty(bodyText)) {
            //                        htmlEmail.setTextMsg(bodyText);
            //                    }
            email = htmlEmail;
            //                }
            MultiPartEmail multiPartEmail = (MultiPartEmail) email;
            List<EmailAttachment> objectList = (List<EmailAttachment>) infoMap.get(ATTACHMENTS);
            for (EmailAttachment object : objectList) {
                multiPartEmail.attach(object);
            }
        }
        if (from != null) {
            try {
                InternetAddress iAddress = new InternetAddress(from.toString());
                email.setFrom(iAddress.getAddress(), iAddress.getPersonal());
            } catch (Exception e) {
                email.setFrom(from.toString());
            }
        }
        if (replyTo != null) {
            try {
                InternetAddress iAddress = new InternetAddress(replyTo.toString());
                email.addReplyTo(iAddress.getAddress(), iAddress.getPersonal());
            } catch (Exception e) {
                email.addReplyTo(replyTo.toString());
            }
        }
        if (recipientList != null) {
            for (Object recipient : recipientList) {
                try {
                    InternetAddress iAddress = new InternetAddress(recipient.toString());
                    email.addTo(iAddress.getAddress(), iAddress.getPersonal());
                } catch (Exception e) {
                    email.addTo(recipient.toString());
                }
            }
        } else {
            throw new MailException("You must specify at least one recipient.");
        }
        List<Object> ccsList = (List<Object>) infoMap.get(CCS);
        if (ccsList != null) {
            for (Object cc : ccsList) {
                email.addCc(cc.toString());
            }
        }
        List<Object> bccsList = (List<Object>) infoMap.get(BCCS);
        if (bccsList != null) {
            for (Object bcc : bccsList) {
                try {
                    InternetAddress iAddress = new InternetAddress(bcc.toString());
                    email.addBcc(iAddress.getAddress(), iAddress.getPersonal());
                } catch (Exception e) {
                    email.addBcc(bcc.toString());
                }
            }
        }
        if (!StringUtils.isEmpty(charset)) {
            email.setCharset(charset);
        }
        email.setSubject(subject);
        email.updateContentType(TEXT_HTML);
        if (headers != null) {
            for (String key : headers.keySet()) {
                email.addHeader(key, headers.get(key));
            }
        }
        // reset the infomap
        infos.remove();
        return Mail.send(email);
    } catch (EmailException ex) {
        throw new MailException("Cannot send email", ex);
    }
}
Example 33
Project: researchzilla-master  File: EmailUtil.java View source code
//TODO complete sendEmail function
public static void sendEmail(String smtp, int port, String username, String password, String from, String subject, String msg, String to) {
    Email emailAgent = new SimpleEmail();
    emailAgent.setHostName(smtp);
    emailAgent.setSmtpPort(port);
    emailAgent.setAuthentication("yumingzhe.pt@gmail.com", "123456");
    emailAgent.setSSL(true);
    try {
        emailAgent.setFrom(from);
        emailAgent.setSubject(subject);
        emailAgent.setCharset("utf8");
        emailAgent.setMsg(msg);
        emailAgent.addTo(to);
        emailAgent.send();
    } catch (EmailException e) {
        e.printStackTrace();
    }
}
Example 34
Project: sling-master  File: SimpleMailBuilderIT.java View source code
@Test
public void testBuildWithDefaults() throws Exception {
    final MailBuilder mailBuilder = getService(MailBuilder.class);
    final Email email = mailBuilder.build("Stop your messing around, Better think of your future...", "rudy@ghosttown", Collections.emptyMap());
    email.buildMimeMessage();
    final byte[] bytes = MailUtil.toByteArray(email);
    final String mail = new String(bytes, StandardCharsets.UTF_8);
    logger.debug("mail: " + mail);
    assertEquals("rudy@ghosttown", email.getToAddresses().get(0).getAddress());
    assertEquals("Rudy, A Message to You", email.getSubject());
    assertEquals("dandy.livingstone@kingston.jamaica", email.getFromAddress().getAddress());
    assertEquals("localhost", email.getHostName());
    logger.debug(email.getMimeMessage().getContent().toString());
}
Example 35
Project: sonar-plugins-master  File: EmailPublisher.java View source code
Email getEmail(Project project) throws EmailException {
    Configuration configuration = project.getConfiguration();
    SonarEmail email = newEmail();
    String host = configuration.getString(HOST_PROPERTY, SMTP_HOST_DEFAULT_VALUE);
    String port = configuration.getString(PORT_PROPERTY, PORT_DEFAULT_VALUE);
    String username = configuration.getString(USERNAME_PROPERTY);
    String password = configuration.getString(PASSWORD_PROPERTY);
    boolean withTLS = configuration.getBoolean(TLS_PROPERTY, TLS_DEFAULT_VALUE);
    String from = configuration.getString(FROM_PROPERTY, "");
    String to = configuration.getString(TO_PROPERTY, "");
    email.setHostName(host);
    email.setSmtpPort(port);
    if (!StringUtils.isBlank(username) || !StringUtils.isBlank(password)) {
        email.setAuthentication(username, password);
    }
    email.setTLS(withTLS);
    email.setFrom(from);
    String[] addrs = StringUtils.split(to, "\t\r\n;, ");
    for (String addr : addrs) {
        email.addTo(addr);
    }
    email.setSubject(String.format("Sonar analysis of %s", project.getName()));
    email.setMsg(String.format("Sonar analysis of %s available %s%s%s", project.getName(), server.getURL(), PROJECT_INDEX_URI, project.getKey()));
    return email;
}
Example 36
Project: structr-master  File: MailHelper.java View source code
private static void setup(final Email mail, final String to, final String toName, final String from, final String fromName, final String cc, final String bcc, final String bounce, final String subject) throws EmailException {
    // FIXME: this might be slow if the config file is read each time
    final String smtpHost = Settings.SmtpHost.getValue();
    final int smtpPort = Settings.SmtpPort.getValue();
    final String smtpUser = Settings.SmtpUser.getValue();
    final String smtpPassword = Settings.SmtpPassword.getValue();
    final boolean smtpUseTLS = Settings.SmtpTlsEnabled.getValue();
    final boolean smtpRequireTLS = Settings.SmtpTlsRequired.getValue();
    mail.setCharset(charset);
    mail.setHostName(smtpHost);
    mail.setSmtpPort(smtpPort);
    mail.setStartTLSEnabled(smtpUseTLS);
    mail.setStartTLSRequired(smtpRequireTLS);
    mail.setCharset(charset);
    if (StringUtils.isNotBlank(smtpUser) && StringUtils.isNotBlank(smtpPassword)) {
        mail.setAuthentication(smtpUser, smtpPassword);
    }
    mail.addTo(to, toName);
    mail.setFrom(from, fromName);
    if (StringUtils.isNotBlank(cc)) {
        mail.addCc(cc);
    }
    if (StringUtils.isNotBlank(bcc)) {
        mail.addBcc(bcc);
    }
    if (StringUtils.isNotBlank(bounce)) {
        mail.setBounceAddress(bounce);
    }
    mail.setSubject(subject);
}
Example 37
Project: TechnologyReadinessTool-master  File: EmailServiceImpl.java View source code
private void setupEmail(Email email) throws EmailException {
    email.setHostName(getHostName());
    email.setSslSmtpPort(getSmtpPort());
    email.setFrom(getReplyAddress(), getReplyName());
    if (StringUtils.isNotBlank(useSsl)) {
        email.setSSL(Boolean.valueOf(getUseSsl()));
        email.setSslSmtpPort(getSslPort());
    }
    if (StringUtils.isNotBlank(useTls)) {
        email.setTLS(Boolean.valueOf(getUseTls()));
    }
    // use authentication if configured
    if (StringUtils.isNotBlank(getAuthenticationUserName())) {
        email.setAuthenticator(new DefaultAuthenticator(getAuthenticationUserName(), getAuthenticationPassword()));
    }
}
Example 38
Project: ABRAID-MP-master  File: EmailServiceTest.java View source code
@Test
public void sendEmailCorrectlySetsUpSMTP() throws Exception {
    // Arrange
    SmtpConfiguration expectation = arrangeSMTP();
    Email email = mock(Email.class);
    EmailServiceImpl target = new EmailServiceImpl(arrangeEmailFactory(email), "", "", expectation, new Class[0], new File[0]);
    // Act
    target.sendEmail("", "", "");
    // Assert
    verify(email).setHostName(expectation.getAddress());
    verify(email).setSmtpPort(expectation.getPort());
    verify(email).setSslSmtpPort("" + expectation.getPort());
    verify(email).setStartTLSRequired(expectation.useSSL());
    ArgumentCaptor<DefaultAuthenticator> captor = captorForClass(DefaultAuthenticator.class);
    verify(email).setAuthenticator(captor.capture());
    DefaultAuthenticator authenticator = captor.getValue();
    Field protectedField = DefaultAuthenticator.class.getDeclaredField("authentication");
    protectedField.setAccessible(true);
    PasswordAuthentication authentication = (PasswordAuthentication) protectedField.get(authenticator);
    assertThat(authentication.getUserName()).isEqualTo(expectation.getUsername());
    assertThat(authentication.getPassword()).isEqualTo(expectation.getPassword());
}
Example 39
Project: acs-aem-commons-master  File: EmailServiceImpl.java View source code
@Override
public List<InternetAddress> sendEmail(final String templatePath, final Map<String, String> emailParams, final InternetAddress... recipients) {
    List<InternetAddress> failureList = new ArrayList<InternetAddress>();
    if (recipients == null || recipients.length <= 0) {
        throw new IllegalArgumentException("Invalid Recipients");
    }
    final MailTemplate mailTemplate = this.getMailTemplate(templatePath);
    final Class<? extends Email> mailType = this.getMailType(templatePath);
    final MessageGateway<Email> messageGateway = messageGatewayService.getGateway(mailType);
    for (final InternetAddress address : recipients) {
        try {
            // Get a new email per recipient to avoid duplicate attachments
            final Email email = getEmail(mailTemplate, mailType, emailParams);
            email.setTo(Collections.singleton(address));
            messageGateway.send(email);
        } catch (Exception e) {
            failureList.add(address);
            log.error("Error sending email to [ " + address + " ]", e);
        }
    }
    return failureList;
}
Example 40
Project: activiti-engine-5.12-master  File: MailActivityBehavior.java View source code
public void execute(ActivityExecution execution) {
    String toStr = getStringFromField(to, execution);
    String fromStr = getStringFromField(from, execution);
    String ccStr = getStringFromField(cc, execution);
    String bccStr = getStringFromField(bcc, execution);
    String subjectStr = getStringFromField(subject, execution);
    String textStr = getStringFromField(text, execution);
    String htmlStr = getStringFromField(html, execution);
    String charSetStr = getStringFromField(charset, execution);
    Email email = createEmail(textStr, htmlStr);
    addTo(email, toStr);
    setFrom(email, fromStr);
    addCc(email, ccStr);
    addBcc(email, bccStr);
    setSubject(email, subjectStr);
    setMailServerProperties(email);
    setCharset(email, charSetStr);
    try {
        email.send();
    } catch (EmailException e) {
        throw new ActivitiException("Could not send e-mail", e);
    }
    leave(execution);
}
Example 41
Project: activiti-engine-ppi-master  File: MailActivityBehavior.java View source code
public void execute(ActivityExecution execution) {
    String toStr = getStringFromField(to, execution);
    String fromStr = getStringFromField(from, execution);
    String ccStr = getStringFromField(cc, execution);
    String bccStr = getStringFromField(bcc, execution);
    String subjectStr = getStringFromField(subject, execution);
    String textStr = getStringFromField(text, execution);
    String htmlStr = getStringFromField(html, execution);
    String charSetStr = getStringFromField(charset, execution);
    Email email = createEmail(textStr, htmlStr);
    addTo(email, toStr);
    setFrom(email, fromStr);
    addCc(email, ccStr);
    addBcc(email, bccStr);
    setSubject(email, subjectStr);
    setMailServerProperties(email);
    setCharset(email, charSetStr);
    try {
        email.send();
    } catch (EmailException e) {
        throw new ActivitiException("Could not send e-mail", e);
    }
    leave(execution);
}
Example 42
Project: alkacon-oamp-master  File: CmsNewsletterMailData.java View source code
/**
     * Returns the mail to send as newsletter, with set subject, text and from address.<p>
     * 
     * @return the mail to send as newsletter
     * @throws CmsException if generating the email content fails
     */
@Override
public Email getEmail() throws CmsException {
    // get the email data from the content fields
    String from = getFrom();
    String fromName = getFromName();
    String subject = getSubject();
    if (isHtmlMail()) {
        // create and send HTML email
        CmsHtmlMail mail = new CmsHtmlMail();
        try {
            if (CmsStringUtil.isEmptyOrWhitespaceOnly(fromName)) {
                mail.setFrom(from);
            } else {
                mail.setFrom(from, fromName);
            }
        } catch (EmailException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_NEWSLETTER_EMAIL_FROM_2, from, getContent().getFile().getRootPath()));
            }
        }
        mail.setSubject(subject);
        try {
            // create the email content and use it as HTML message
            mail.setHtmlMsg(getHtml());
            // check if HTML only mail should be sent by evaluating the optional element
            if (!isHtmlOnly()) {
                mail.setTextMsg(getText());
            }
        } catch (EmailException e) {
        }
        // set the mail encoding
        mail.setCharset(getEncoding());
        return mail;
    } else {
        // create and send text only email
        CmsSimpleMail mail = new CmsSimpleMail();
        try {
            if (CmsStringUtil.isEmptyOrWhitespaceOnly(fromName)) {
                mail.setFrom(from);
            } else {
                mail.setFrom(from, fromName);
            }
        } catch (EmailException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_NEWSLETTER_EMAIL_FROM_2, from, getContent().getFile().getRootPath()));
            }
        }
        mail.setSubject(subject);
        // extract the text from the HTML field
        try {
            mail.setMsg(getText());
        } catch (Exception e) {
        }
        // set the mail encoding
        mail.setCharset(getEncoding());
        return mail;
    }
}
Example 43
Project: computoser-master  File: EmailService.java View source code
private Email createEmail(boolean html) {
    Email e = null;
    if (html) {
        e = new HtmlEmail();
    } else {
        e = new SimpleEmail();
    }
    e.setHostName(smtpHost);
    if (!StringUtils.isEmpty(smtpUser)) {
        e.setAuthentication(smtpUser, smtpPassword);
    }
    if (!StringUtils.isEmpty(smtpBounceEmail)) {
        e.setBounceAddress(smtpBounceEmail);
    }
    e.setTLS(true);
    //tls port
    e.setSmtpPort(587);
    e.setCharset("UTF8");
    return e;
}
Example 44
Project: coprhd-controller-master  File: MailSettingsValidator.java View source code
private static Email buildMessage(Email email, Settings form) throws EmailException {
    String from = form.fromAddress;
    if (email.getFromAddress() == null && !StringUtils.isEmpty(from)) {
        email.setFrom(from);
    } else if (email.getFromAddress() == null) {
        throw new EmailException("Please define a 'from' email address");
    }
    if ((email.getToAddresses() == null || email.getToAddresses().size() == 0) && (email.getCcAddresses() == null || email.getCcAddresses().size() == 0) && (email.getBccAddresses() == null || email.getBccAddresses().size() == 0)) {
        throw new EmailException("Please define a recipient email address");
    }
    if (email.getSubject() == null) {
        throw new EmailException("Please define a subject");
    }
    if (email.getReplyToAddresses() == null || email.getReplyToAddresses().size() == 0) {
        email.addReplyTo(email.getFromAddress().getAddress());
    }
    return email;
}
Example 45
Project: FiWare-Template-Handler-master  File: MailActivityBehavior.java View source code
public void execute(ActivityExecution execution) {
    String toStr = getStringFromField(to, execution);
    String fromStr = getStringFromField(from, execution);
    String ccStr = getStringFromField(cc, execution);
    String bccStr = getStringFromField(bcc, execution);
    String subjectStr = getStringFromField(subject, execution);
    String textStr = getStringFromField(text, execution);
    String htmlStr = getStringFromField(html, execution);
    String charSetStr = getStringFromField(charset, execution);
    Email email = createEmail(textStr, htmlStr);
    addTo(email, toStr);
    setFrom(email, fromStr);
    addCc(email, ccStr);
    addBcc(email, bccStr);
    setSubject(email, subjectStr);
    setMailServerProperties(email);
    setCharset(email, charSetStr);
    try {
        email.send();
    } catch (EmailException e) {
        throw new ActivitiException("Could not send e-mail", e);
    }
    leave(execution);
}
Example 46
Project: graylog2-server-master  File: FormattedEmailAlertSender.java View source code
private void sendEmail(String emailAddress, Stream stream, AlertCondition.CheckResult checkResult, List<Message> backlog) throws TransportConfigurationException, EmailException {
    LOG.debug("Sending mail to " + emailAddress);
    if (!configuration.isEnabled()) {
        throw new TransportConfigurationException("Email transport is not enabled in server configuration file!");
    }
    final Email email = new SimpleEmail();
    email.setCharset(EmailConstants.UTF_8);
    if (isNullOrEmpty(configuration.getHostname())) {
        throw new TransportConfigurationException("No hostname configured for email transport while trying to send alert email!");
    } else {
        email.setHostName(configuration.getHostname());
    }
    email.setSmtpPort(configuration.getPort());
    if (configuration.isUseSsl()) {
        email.setSslSmtpPort(Integer.toString(configuration.getPort()));
    }
    if (configuration.isUseAuth()) {
        email.setAuthenticator(new DefaultAuthenticator(Strings.nullToEmpty(configuration.getUsername()), Strings.nullToEmpty(configuration.getPassword())));
    }
    email.setSSLOnConnect(configuration.isUseSsl());
    email.setStartTLSEnabled(configuration.isUseTls());
    if (pluginConfig != null && !isNullOrEmpty(pluginConfig.getString("sender"))) {
        email.setFrom(pluginConfig.getString("sender"));
    } else {
        email.setFrom(configuration.getFromEmail());
    }
    email.setSubject(buildSubject(stream, checkResult, backlog));
    email.setMsg(buildBody(stream, checkResult, backlog));
    email.addTo(emailAddress);
    email.send();
}
Example 47
Project: InSpider-master  File: EtlJobMail.java View source code
@Override
public void sendMail(Job originalJob) throws EmailException {
    if (!(originalJob instanceof EtlJob)) {
        return;
    }
    final EtlJob job = (EtlJob) originalJob;
    if (job.getStatus() == Status.ABORTED || managerDao.getJobLogCount(job, LogLevel.ERROR) > 0) {
        technicalLog.debug("Job is aborted or resulted in errors, trying to send e-mail");
        String jobtype = JobTypeIntrospector.getJobTypeName(job);
        if (!jobtype.equals("TRANSFORM")) {
            Bronhouder bronhouder = job.getBronhouder();
            if (bronhouder != null) {
                String address = bronhouder.getContactEmailadres();
                String extraAddress = bronhouder.getContactExtraEmailadres();
                Email mail = new SimpleEmail();
                mail.setHostName(smtpHost);
                mail.setSmtpPort(smtpPort);
                mail.setFrom(from);
                mail.setSubject(subject);
                mail.setMsg(createMsg(job));
                mail.addTo(address);
                if (extraAddress != null && !extraAddress.isEmpty()) {
                    mail.addTo(extraAddress);
                }
                mail.send();
                technicalLog.debug("E-mail sent to: " + address);
            } else {
                technicalLog.error("Couldn't send e-mail, no bronhouder found");
            }
        } else {
            // happens for transform jobs
            technicalLog.debug("Couldn't send e-mail, transform job");
        }
    } else {
        technicalLog.debug("Job is not aborted and doesn't contain errors");
        String jobtype = JobTypeIntrospector.getJobTypeName(job);
        technicalLog.debug("jobtype: " + jobtype);
        if (jobtype.equals("ImportJob")) {
            if (job.getVerversen()) {
                String emailTeksten = job.getDatasetType().getThema().getEmailteksten();
                if (emailTeksten == null || emailTeksten.isEmpty()) {
                    technicalLog.debug("No Email Teksten template defined in Emailteksten tab");
                    return;
                }
                Bronhouder bronhouder = job.getBronhouder();
                if (bronhouder != null) {
                    String address = bronhouder.getContactEmailadres();
                    String extraAddress = bronhouder.getContactExtraEmailadres();
                    Email mail = new SimpleEmail();
                    mail.setHostName(smtpHost);
                    mail.setSmtpPort(smtpPort);
                    mail.setFrom(from);
                    mail.setSubject(subject);
                    mail.setMsg(createSuccessMsg(job));
                    mail.addTo(address);
                    if (extraAddress != null && !extraAddress.isEmpty()) {
                        mail.addTo(extraAddress);
                    }
                    mail.send();
                    technicalLog.debug("E-mail sent to: " + address);
                } else {
                    technicalLog.error("Couldn't send e-mail, no bronhouder found");
                }
            }
        }
    }
}
Example 48
Project: jenkow-plugin-master  File: MailActivityBehavior.java View source code
public void execute(ActivityExecution execution) {
    String toStr = getStringFromField(to, execution);
    String fromStr = getStringFromField(from, execution);
    String ccStr = getStringFromField(cc, execution);
    String bccStr = getStringFromField(bcc, execution);
    String subjectStr = getStringFromField(subject, execution);
    String textStr = getStringFromField(text, execution);
    String htmlStr = getStringFromField(html, execution);
    String charSetStr = getStringFromField(charset, execution);
    Email email = createEmail(textStr, htmlStr);
    addTo(email, toStr);
    setFrom(email, fromStr);
    addCc(email, ccStr);
    addBcc(email, bccStr);
    setSubject(email, subjectStr);
    setMailServerProperties(email);
    setCharset(email, charSetStr);
    try {
        email.send();
    } catch (EmailException e) {
        throw new ActivitiException("Could not send e-mail", e);
    }
    leave(execution);
}
Example 49
Project: mangooio-master  File: Mail.java View source code
private void sendSimpleEmail() throws MangooMailerException {
    try {
        Email email = new SimpleEmail();
        email.setCharset(Default.ENCODING.toString());
        email.setHostName(host);
        email.setSmtpPort(port);
        email.setAuthenticator(defaultAuthenticator);
        email.setSSLOnConnect(ssl);
        email.setFrom(this.from);
        email.setSubject(this.subject);
        email.setMsg(render());
        for (String recipient : this.recipients) {
            email.addTo(recipient);
        }
        for (String cc : this.ccRecipients) {
            email.addCc(cc);
        }
        for (String bcc : this.bccRecipients) {
            email.addBcc(bcc);
        }
        email.send();
    } catch (EmailExceptionMangooTemplateEngineException |  e) {
        throw new MangooMailerException(e);
    }
}
Example 50
Project: njexl-master  File: Utils.java View source code
static Email createEmail(String subject, String from) {
    try {
        Email email = new SimpleEmail();
        email.setHostName(SMTP_HOST);
        email.setSmtpPort(SMTP_PORT);
        email.setAuthenticator(defaultAuthenticator);
        if (!from.contains("@")) {
            from += "@" + MAIL_DOMAIN;
        }
        email.setFrom(from);
        email.setSubject(subject);
        return email;
    } catch (Exception e) {
        System.err.println("Can not create e-mail : " + e);
    }
    return null;
}
Example 51
Project: opencms-modules-master  File: CmsNewsletterMailData.java View source code
/**
     * Returns the mail to send as newsletter, with set subject, text and from address.<p>
     * 
     * @return the mail to send as newsletter
     * @throws CmsException if generating the email content fails
     */
@Override
public Email getEmail() throws CmsException {
    // get the email data from the content fields
    String from = getFrom();
    String fromName = getFromName();
    String subject = getSubject();
    if (isHtmlMail()) {
        // create and send HTML email
        CmsHtmlMail mail = new CmsHtmlMail();
        try {
            if (CmsStringUtil.isEmptyOrWhitespaceOnly(fromName)) {
                mail.setFrom(from);
            } else {
                mail.setFrom(from, fromName);
            }
        } catch (EmailException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_NEWSLETTER_EMAIL_FROM_2, from, getContent().getFile().getRootPath()));
            }
        }
        mail.setSubject(subject);
        try {
            // create the email content and use it as HTML message
            mail.setHtmlMsg(getHtml());
            // check if HTML only mail should be sent by evaluating the optional element
            if (!isHtmlOnly()) {
                mail.setTextMsg(getText());
            }
        } catch (EmailException e) {
        }
        // set the mail encoding
        mail.setCharset(getEncoding());
        return mail;
    } else {
        // create and send text only email
        CmsSimpleMail mail = new CmsSimpleMail();
        try {
            if (CmsStringUtil.isEmptyOrWhitespaceOnly(fromName)) {
                mail.setFrom(from);
            } else {
                mail.setFrom(from, fromName);
            }
        } catch (EmailException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_NEWSLETTER_EMAIL_FROM_2, from, getContent().getFile().getRootPath()));
            }
        }
        mail.setSubject(subject);
        // extract the text from the HTML field
        try {
            mail.setMsg(getText());
        } catch (Exception e) {
        }
        // set the mail encoding
        mail.setCharset(getEncoding());
        return mail;
    }
}
Example 52
Project: openhab1-addons-master  File: Mail.java View source code
/**
     * Sends an email with attachment(s) via SMTP
     *
     * @param to the email address of the recipient
     * @param subject the subject of the email
     * @param message the body of the email
     * @param attachmentUrlList a list of URL strings of the contents to send as attachments
     *
     * @return <code>true</code>, if sending the email has been successful and
     *         <code>false</code> in all other cases.
     */
@ActionDoc(text = "Sends an email with attachment via SMTP")
public static boolean sendMail(@ParamDoc(name = "to") String to, @ParamDoc(name = "subject") String subject, @ParamDoc(name = "message") String message, @ParamDoc(name = "attachmentUrlList") List<String> attachmentUrlList) {
    boolean success = false;
    if (MailActionService.isProperlyConfigured) {
        Email email = new SimpleEmail();
        if (attachmentUrlList != null && !attachmentUrlList.isEmpty()) {
            email = new MultiPartEmail();
            for (String attachmentUrl : attachmentUrlList) {
                // Create the attachment
                try {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setURL(new URL(attachmentUrl));
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    String fileName = attachmentUrl.replaceFirst(".*/([^/?]+).*", "$1");
                    attachment.setName(isNotBlank(fileName) ? fileName : "Attachment");
                    ((MultiPartEmail) email).attach(attachment);
                } catch (MalformedURLException e) {
                    logger.error("Invalid attachment url.", e);
                } catch (EmailException e) {
                    logger.error("Error adding attachment to email.", e);
                }
            }
        }
        email.setHostName(hostname);
        email.setSmtpPort(port);
        email.setStartTLSEnabled(startTLSEnabled);
        email.setSSLOnConnect(sslOnConnect);
        if (isNotBlank(username)) {
            if (popBeforeSmtp) {
                email.setPopBeforeSmtp(true, hostname, username, password);
            } else {
                email.setAuthenticator(new DefaultAuthenticator(username, password));
            }
        }
        try {
            if (isNotBlank(charset)) {
                email.setCharset(charset);
            }
            email.setFrom(from);
            String[] toList = to.split(";");
            for (String toAddress : toList) {
                email.addTo(toAddress);
            }
            if (!isEmpty(subject)) {
                email.setSubject(subject);
            }
            if (!isEmpty(message)) {
                email.setMsg(message);
            }
            email.send();
            logger.debug("Sent email to '{}' with subject '{}'.", to, subject);
            success = true;
        } catch (EmailException e) {
            logger.error("Could not send e-mail to '" + to + "'.", e);
        }
    } else {
        logger.error("Cannot send e-mail because of missing configuration settings. The current settings are: " + "Host: '{}', port '{}', from '{}', startTLSEnabled: {}, sslOnConnect: {}, username: '{}', password '{}'", new Object[] { hostname, String.valueOf(port), from, String.valueOf(startTLSEnabled), String.valueOf(sslOnConnect), username, password });
    }
    return success;
}
Example 53
Project: paxml-master  File: EmailTag.java View source code
@Override
protected Object doInvoke(Context context) throws Exception {
    if (isolate) {
        Set<String> all = new LinkedHashSet<String>();
        if (to != null) {
            all.addAll(to);
        }
        if (cc != null) {
            all.addAll(cc);
        }
        if (bcc != null) {
            all.addAll(bcc);
        }
        List<String> ids = new ArrayList<String>(all.size());
        for (String r : all) {
            Email email = createEmail(Arrays.asList(r), null, null);
            String id = email.send();
            if (log.isDebugEnabled()) {
                log.debug("Isolated email sent to: " + r + ", from: " + from + ", replyTo: " + replyTo);
            }
            ids.add(id);
        }
        return ids;
    } else {
        Email email = createEmail(to, cc, bcc);
        String id = email.send();
        if (log.isDebugEnabled()) {
            log.debug("Email sent to: " + to + ", cc: " + cc + ", bcc: " + bcc + ", from: " + from + ", replyTo: " + replyTo);
        }
        return id;
    }
}
Example 54
Project: Portofino-master  File: DefaultMailSender.java View source code
public int runOnce(Set<String> idsToMarkAsSent) {
    List<String> ids;
    try {
        ids = queue.getEnqueuedEmailIds();
    } catch (Throwable e) {
        logger.error("Couldn't read email queue", e);
        return -1;
    }
    int serverErrors = 0;
    for (String id : ids) {
        if (idsToMarkAsSent.contains(id)) {
            logger.info("Mail with id {} already sent but mark failed, retrying", id);
            try {
                queue.markSent(id);
                idsToMarkAsSent.remove(id);
            } catch (Throwable e) {
                logger.error("Couldn't mark mail as sent", e);
            }
            continue;
        }
        Email email;
        try {
            email = queue.loadEmail(id);
        } catch (MailParseException e) {
            logger.error("Mail with id " + id + " is corrupted, marking as failed", e);
            markFailed(id, e);
            continue;
        } catch (Throwable e) {
            logger.error("Unexpected error loading mail with id " + id + ", skipping", e);
            continue;
        }
        if (email != null) {
            boolean sent = false;
            try {
                logger.info("Sending email with id {}", id);
                send(email);
                sent = true;
            } catch (EmailException e) {
                Throwable cause = e.getCause();
                if (cause instanceof ParseException || cause instanceof IllegalWriteException || cause instanceof MethodNotSupportedException) {
                    markFailed(id, cause);
                } else if (cause instanceof MessagingException) {
                    if (e.getCause() instanceof SendFailedException && e.getCause().getCause() instanceof SMTPAddressFailedException) {
                        logger.warn("Mail not sent due to known server error, marking as failed");
                        markFailed(id, e);
                    } else {
                        logger.warn("Mail not sent due to known server error, NOT marking as failed", e);
                        serverErrors++;
                    }
                } else {
                    markFailed(id, e);
                }
            } catch (Throwable e) {
                markFailed(id, e);
            }
            if (sent)
                try {
                    logger.info("Email with id {} sent, marking as sent ", id);
                    queue.markSent(id);
                } catch (Throwable e) {
                    logger.error("Couldn't mark mail as sent", e);
                    idsToMarkAsSent.add(id);
                }
        }
    }
    return serverErrors;
}
Example 55
Project: railo-master  File: HtmlEmailImpl.java View source code
/**
     * @throws EmailException EmailException
     * @throws MessagingException MessagingException
     */
private void buildAttachments() throws MessagingException, EmailException {
    MimeMultipart container = this.getContainer();
    MimeMultipart subContainer = null;
    MimeMultipart subContainerHTML = new MimeMultipart("related");
    BodyPart msgHtml = null;
    BodyPart msgText = null;
    container.setSubType("mixed");
    subContainer = new MimeMultipart("alternative");
    if (!StringUtil.isEmpty(this.text)) {
        msgText = new MimeBodyPart();
        subContainer.addBodyPart(msgText);
        if (!StringUtil.isEmpty(this.charset)) {
            msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset);
        } else {
            msgText.setContent(this.text, Email.TEXT_PLAIN);
        }
    }
    if (!StringUtil.isEmpty(this.html)) {
        if (this.inlineImages.size() > 0) {
            msgHtml = new MimeBodyPart();
            subContainerHTML.addBodyPart(msgHtml);
        } else {
            msgHtml = new MimeBodyPart();
            subContainer.addBodyPart(msgHtml);
        }
        if (!StringUtil.isEmpty(this.charset)) {
            msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset);
        } else {
            msgHtml.setContent(this.html, Email.TEXT_HTML);
        }
        Iterator iter = this.inlineImages.iterator();
        while (iter.hasNext()) {
            subContainerHTML.addBodyPart((BodyPart) iter.next());
        }
    }
    // add sub containers to message
    this.addPart(subContainer, 0);
    if (this.inlineImages.size() > 0) {
        // add sub container to message
        this.addPart(subContainerHTML, 1);
    }
}
Example 56
Project: Spy2Servers-master  File: EMailUtils.java View source code
/**
     * <p>
     * parse email receivers info from the map and add to the email receivers list</p>
     *
     * @param email commons email instance.
     * @param receivers receivers map
     * @throws EmailException Email about exception.
     */
private static void parseReceivers(Email email, Map<String, String> receivers) throws EmailException {
    if (receivers != null && receivers.size() > 0) {
        Iterator<Map.Entry<String, String>> iter = receivers.entrySet().iterator();
        Map.Entry<String, String> receiver;
        while (iter.hasNext()) {
            receiver = iter.next();
            email.addTo(receiver.getKey(), receiver.getValue());
        }
    }
}
Example 57
Project: xbpm5-master  File: MailActivityBehavior.java View source code
public void execute(ActivityExecution execution) {
    String toStr = getStringFromField(to, execution);
    String fromStr = getStringFromField(from, execution);
    String ccStr = getStringFromField(cc, execution);
    String bccStr = getStringFromField(bcc, execution);
    String subjectStr = getStringFromField(subject, execution);
    String textStr = getStringFromField(text, execution);
    String htmlStr = getStringFromField(html, execution);
    String charSetStr = getStringFromField(charset, execution);
    Email email = createEmail(textStr, htmlStr);
    addTo(email, toStr);
    setFrom(email, fromStr);
    addCc(email, ccStr);
    addBcc(email, bccStr);
    setSubject(email, subjectStr);
    setMailServerProperties(email);
    setCharset(email, charSetStr);
    try {
        email.send();
    } catch (EmailException e) {
        throw new ActivitiException("Could not send e-mail", e);
    }
    leave(execution);
}
Example 58
Project: XCoLab-master  File: SiteMonitor.java View source code
public void go() throws Exception {
    // read monitor rules
    URL configUrl = SiteMonitor.class.getResource("/siteMonitor-config.xml");
    Serializer serializer = new Persister();
    final SiteMonitorConfig config = serializer.read(SiteMonitorConfig.class, new File(configUrl.getFile()));
    for (CheckerConfig checkerConfig : config.getCheckers()) {
        PageChecker checker = (PageChecker) SiteMonitor.class.getClassLoader().loadClass(checkerConfig.getClasz()).newInstance();
        checker.configure(checkerConfig.getConfiguration(), checkerConfig.getMessage(), this);
        pageCheckers.put(checkerConfig.getName(), checker);
    }
    for (CheckerMapping mapping : config.getCheckerMappings()) {
        _log.info("using checker: " + mapping.getChecker());
        if (!pageCheckers.containsKey(mapping.getChecker())) {
            throw new RuntimeException("Can't find page checker for name (in mapping) " + mapping.getChecker());
        }
    }
    checkerMappings.addAll(config.getCheckerMappings());
    if (oldErrorsFile.exists()) {
        BufferedReader bis = new BufferedReader(new FileReader(oldErrorsFile));
        String line = null;
        while ((line = bis.readLine()) != null) {
            oldErrors.add(line);
        }
        bis.close();
    }
    for (CrawlConfig crawlConfig : config.getCrawlerConfig()) {
        urlsToCrawl.add(new UrlToCrawl(crawlConfig.getUrl(), 0, crawlConfig));
    }
    while (!urlsToCrawl.isEmpty()) {
        doCrawl(urlsToCrawl.poll());
    }
    BufferedWriter oldErrorsWriter = new BufferedWriter(new FileWriter(oldErrorsFile));
    if (!detectedErrorsByUrl.isEmpty()) {
        for (Map.Entry<String, Set<DetectedError>> entry : detectedErrorsByUrl.entrySet()) {
            StringBuilder emailNewUrlErrors = new StringBuilder();
            for (DetectedError error : entry.getValue()) {
                _log.info("FOUND ERROR: " + error.getMessage());
                if (!oldErrors.contains(getUrlCheckerErrorKey(entry.getKey(), error.getChecker()))) {
                    emailNewUrlErrors.append("\t");
                    emailNewUrlErrors.append(error.getChecker());
                    emailNewUrlErrors.append("\n\t\t");
                    emailNewUrlErrors.append(error.getMessage());
                    emailNewUrlErrors.append("\n");
                }
                oldErrorsWriter.write(getUrlCheckerErrorKey(entry.getKey(), error.getChecker()));
                oldErrorsWriter.write('\n');
            }
            if (emailNewUrlErrors.length() > 0) {
                emailBuilder.append(entry.getKey());
                emailBuilder.append('\n');
                emailBuilder.append(emailNewUrlErrors.toString());
                emailBuilder.append("\n");
            }
        }
        oldErrorsWriter.flush();
        oldErrorsWriter.close();
    }
    // send email notifications
    if (config.getEmailNotificationConfig() != null && emailBuilder.length() > 0) {
        Email email = new SimpleEmail();
        email.setHostName(config.getEmailNotificationConfig().getSmtphost());
        if (config.getEmailNotificationConfig().getPort() > 0) {
            email.setSmtpPort(config.getEmailNotificationConfig().getPort());
        }
        if (config.getEmailNotificationConfig().isUseTsl()) {
            email.setSSLOnConnect(true);
        }
        email.setFrom(config.getEmailNotificationConfig().getFrom());
        email.setSubject(config.getEmailNotificationConfig().getSubject());
        email.setMsg(emailBuilder.toString());
        for (String to : config.getEmailNotificationConfig().getTo()) {
            email.addTo(to);
        }
        if (config.getEmailNotificationConfig().getSmtpuser() != null && config.getEmailNotificationConfig().getSmtppassword() != null) {
            email.setAuthentication(config.getEmailNotificationConfig().getSmtpuser(), config.getEmailNotificationConfig().getSmtppassword());
        }
        email.send();
        _log.info("Sent email.");
    }
}
Example 59
Project: japid42-master  File: Mail.java View source code
/**
	 * Send an email
	 */
public static Future<Boolean> send(Email email) {
    try {
        email = buildMessage(email);
        // has to use this since mail.smtp is a tree in play2
        String string = getConfig("mail.smtp.host");
        if (string != null)
            if (string.equals("mock") && Play.isDev()) {
                Mock.send(email);
                return new Future<Boolean>() {

                    public boolean cancel(boolean mayInterruptIfRunning) {
                        return false;
                    }

                    public boolean isCancelled() {
                        return false;
                    }

                    public boolean isDone() {
                        return true;
                    }

                    public Boolean get() throws InterruptedException, ExecutionException {
                        return true;
                    }

                    public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                        return true;
                    }
                };
            }
        email.setMailSession(getSession());
        return sendMessage(email);
    } catch (EmailException ex) {
        throw new MailException("Cannot send email", ex);
    }
}
Example 60
Project: jwebsocket-master  File: MailPlugIn.java View source code
private void sendMail(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();
    String lFrom = aToken.getString("from", "[unknown]");
    String lTo = aToken.getString("to");
    String lCC = aToken.getString("cc");
    String lBCC = aToken.getString("bcc");
    String lSubject = aToken.getString("subject");
    String lBody = aToken.getString("body");
    Boolean lIsHTML = aToken.getBoolean("html", false);
    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);
    Map lMap = new FastMap();
    if (lFrom != null && lFrom.length() > 0) {
        lMap.put("from", lFrom);
    }
    if (lTo != null && lTo.length() > 0) {
        lMap.put("to", lTo);
    }
    if (lCC != null && lCC.length() > 0) {
        lMap.put("cc", lCC);
    }
    if (lBCC != null && lBCC.length() > 0) {
        lMap.put("bcc", lBCC);
    }
    if (lSubject != null && lSubject.length() > 0) {
        lMap.put("subject", lSubject);
    }
    if (lBody != null && lBody.length() > 0) {
        lMap.put("body", lBody);
    }
    // Create the attachment
    List<EmailAttachment> lAttachments = new FastList<EmailAttachment>();
    // Create the lEmail message
    if (mLog.isDebugEnabled()) {
        mLog.debug("Sending e-mail to " + lTo + " with subject '" + lSubject + "'...");
    }
    try {
        Email lEmail;
        if (lIsHTML) {
            lEmail = new HtmlEmail();
        } else {
            lEmail = new MultiPartEmail();
        }
        lEmail.setHostName(SMTP_HOST);
        lEmail.setSmtpPort(SMTP_PORT);
        if (SMTP_AUTH) {
            lEmail.setAuthentication(SMTP_USER, SMTP_PASSWORD);
        }
        if (SMTP_POP3BEFORE) {
            lEmail.setPopBeforeSmtp(true, POP3_HOST, POP3_USER, POP3_PASSWORD);
        }
        if (lFrom != null && lFrom.length() > 0) {
            lEmail.setFrom(lFrom);
        }
        if (lTo != null && lTo.length() > 0) {
            lEmail.addTo(lTo);
        }
        if (lSubject != null && lSubject.length() > 0) {
            lEmail.setSubject(lSubject);
        }
        if (lBody != null && lBody.length() > 0) {
            if (lIsHTML) {
                HtmlEmail lHTML = ((HtmlEmail) lEmail);
                /*
					URL lURL = new URL("http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg");
					String lCID = ((HtmlEmail )lEmail).embed(lURL, "five feet further logo");

					//url = new URL( "http://five-feet-further.com/resources/css/IJX4FWDocu.css" );
					// String css = ((HtmlEmail)lEmail).embed( url, "name of css" );

					((HtmlEmail )lEmail).setHtmlMsg(
					"<html><body>" +
					"<style type=\"text/css\">" +
					"h1 { " +
					" font-family:arial, helvetica, sans-serif;" +
					" font-weight:bold;" +
					" font-size:18pt;" +
					"}" +
					"</style>" +
					// "<link href=\"cid:" + css + "\" type=\"text/css\" rel=\"stylesheet\">" +
					"<p><img src=\"cid:" + lCID + "\"></p>" +
					"<p><img src=\"http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg\"></p>" +
					lItem +
					"</body></html>");
					 */
                /*
					// Now the message body.
					Multipart mp = new MimeMultipart();

					BodyPart textPart = new MimeBodyPart();
					// sets type to "text/plain"
					textPart.setText("Kann Ihr Browser keine HTML-Mails darstellen?");

					BodyPart pixPart = new MimeBodyPart();
					pixPart.setContent(lMsg, "text/html");

					// Collect the Parts into the MultiPart
					mp.addBodyPart(textPart);
					mp.addBodyPart(pixPart);

					// Put the MultiPart into the Message
					((HtmlEmail) lEmail).setContent((MimeMultipart)mp);
					((HtmlEmail) lEmail).buildMimeMessage();

					/*
					// ((HtmlEmail) lEmail).setContent(lMsg, Email.TEXT_HTML);

					// lHeaders.put("Innotrade-Id", "4711-0815");
					// lHTML.setHeaders(lHeaders);
					// ((HtmlEmail) lEmail).setCharset("UTF-8");
					// ((HtmlEmail) lEmail).setMsg(lMsg);
					lMM.setHeader("Innotrade-Id", "4711-0815");

					// ((HtmlEmail) lEmail).setContent(lTxtMsg, Email.TEXT_PLAIN);
					 */
                // String lTxtMsg = "Your Email-Client does not support HTML messages.";
                lHTML.setHtmlMsg(lBody);
            // lHTML.setTextMsg(lTxtMsg);
            } else {
                lEmail.setMsg(lBody);
            }
        }
        // add attachment(s), if such
        for (EmailAttachment lAttachment : lAttachments) {
            ((MultiPartEmail) lEmail).attach(lAttachment);
        }
        for (int lIdx = 0; lIdx < lAttachments.size(); lIdx++) {
            ((MultiPartEmail) lEmail).attach((EmailAttachment) lAttachments.get(lIdx));
        }
        // send the Email
        String lMsgId = lEmail.send();
        if (mLog.isInfoEnabled()) {
            mLog.info("Email successfully sent" + " from " + (lFrom != null ? lFrom : "(no sender)") + " to " + (lTo != null ? lTo : "(no receipient)") + ", subject " + (lSubject != null ? "'" + lSubject + "'" : "(no subject)") + ", Id " + lMsgId);
        }
        lResponse.setString("id", lMsgId);
    } catch (Exception lEx) {
        String lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }
    // send response to requester
    lServer.sendToken(aConnector, lResponse);
}
Example 61
Project: Lucee-master  File: HtmlEmailImpl.java View source code
/**
     * @throws EmailException EmailException
     * @throws MessagingException MessagingException
     */
private void buildAttachments() throws MessagingException, EmailException {
    MimeMultipart container = this.getContainer();
    MimeMultipart subContainer = null;
    MimeMultipart subContainerHTML = new MimeMultipart("related");
    BodyPart msgHtml = null;
    BodyPart msgText = null;
    container.setSubType("mixed");
    subContainer = new MimeMultipart("alternative");
    if (!StringUtil.isEmpty(this.text)) {
        msgText = new MimeBodyPart();
        subContainer.addBodyPart(msgText);
        if (!StringUtil.isEmpty(this.charset)) {
            msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset);
        } else {
            msgText.setContent(this.text, Email.TEXT_PLAIN);
        }
    }
    if (!StringUtil.isEmpty(this.html)) {
        if (this.inlineImages.size() > 0) {
            msgHtml = new MimeBodyPart();
            subContainerHTML.addBodyPart(msgHtml);
        } else {
            msgHtml = new MimeBodyPart();
            subContainer.addBodyPart(msgHtml);
        }
        if (!StringUtil.isEmpty(this.charset)) {
            msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset);
        } else {
            msgHtml.setContent(this.html, Email.TEXT_HTML);
        }
        Iterator iter = this.inlineImages.iterator();
        while (iter.hasNext()) {
            subContainerHTML.addBodyPart((BodyPart) iter.next());
        }
    }
    // add sub containers to message
    this.addPart(subContainer, 0);
    if (this.inlineImages.size() > 0) {
        // add sub container to message
        this.addPart(subContainerHTML, 1);
    }
}
Example 62
Project: oerworldmap-master  File: UserIndex.java View source code
private void sendMail(String aEmailAddress, String aMessage, String aSubject) {
    Email mail = new SimpleEmail();
    try {
        mail.setMsg(aMessage);
        mail.setHostName(mConf.getString("mail.smtp.host"));
        mail.setSmtpPort(mConf.getInt("mail.smtp.port"));
        String smtpUser = mConf.getString("mail.smtp.user");
        String smtpPass = mConf.getString("mail.smtp.password");
        if (!smtpUser.isEmpty()) {
            mail.setAuthenticator(new DefaultAuthenticator(smtpUser, smtpPass));
        }
        mail.setSSLOnConnect(mConf.getBoolean("mail.smtp.ssl"));
        mail.setStartTLSEnabled(mConf.getBoolean("mail.smtp.tls"));
        mail.setFrom(mConf.getString("mail.smtp.from"), mConf.getString("mail.smtp.sender"));
        mail.setSubject(aSubject);
        mail.addTo(aEmailAddress);
        mail.send();
        Logger.info("Sent\n" + aMessage + "\nto " + aEmailAddress);
    } catch (EmailException e) {
        Logger.error("Failed to send\n" + aMessage + "\nto " + aEmailAddress, e);
    }
}
Example 63
Project: siu-master  File: AdminApp.java View source code
@Override
public void buttonClick(Button.ClickEvent event) {
    String emailTo = get(API.EMAIL_TO);
    String receiverName = get(API.RECEIVER_NAME);
    String hostName = get(API.HOST);
    String port = get(API.PORT);
    String senderLogin = get(API.SENDER_LOGIN);
    String password = get(API.PASSWORD);
    String emailFrom = get(API.EMAIL_FROM);
    String senderName = get(API.SENDER_NAME);
    if (emailTo.isEmpty() || receiverName.isEmpty() || hostName.isEmpty() || port.isEmpty() || senderLogin.isEmpty() || password.isEmpty() || emailFrom.isEmpty() || senderName.isEmpty()) {
        check.getWindow().showNotification("УÑ?тановите вÑ?е параметры");
        return;
    }
    Email email = new SimpleEmail();
    try {
        email.setSubject("ТеÑ?товое пиÑ?ьмо");
        email.setMsg("ТеÑ?товое пиÑ?ьмо");
        email.addTo(emailTo, receiverName);
        email.setHostName(hostName);
        email.setSmtpPort(Integer.parseInt(port));
        email.setTLS(AdminServiceProvider.getBoolProperty(API.TLS));
        email.setAuthentication(senderLogin, password);
        email.setFrom(emailFrom, senderName);
        email.setCharset("utf-8");
        email.send();
    } catch (EmailException e) {
        check.getWindow().showNotification(e.getMessage());
        e.printStackTrace();
        return;
    }
    check.getWindow().showNotification("ПиÑ?ьмо уÑ?пешно отправлено");
}
Example 64
Project: the-fascinator-master  File: EmailNotificationConsumer.java View source code
/**
     * Callback function for incoming messages.
     * 
     * @param message The incoming message
     */
@Override
public void onMessage(Message message) {
    MDC.put("name", name);
    try {
        // Make sure thread priority is correct
        if (!Thread.currentThread().getName().equals(thread.getName())) {
            Thread.currentThread().setName(thread.getName());
            Thread.currentThread().setPriority(thread.getPriority());
        }
        // Get the message details
        String text = ((TextMessage) message).getText();
        JsonSimple config = new JsonSimple(text);
        String oid = config.getString(null, "oid");
        log.info("Received notification request, object id={}", oid);
        // Addresses
        List<String> toList = config.getStringList("to");
        List<String> ccList = config.getStringList("cc");
        String subject = config.getString(defaultSubject, "subject");
        String body = config.getString(defaultBody, "body");
        sendEmails(toList, ccList, subject, body);
        // Log event
        sentMessage(oid, "notify");
        // Finish up
        sendNotification(oid, "emailSent", "(" + name + ") Email notification sent : '" + oid + "'");
    } catch (JMSException jmse) {
        log.error("Failed to send/receive message: {}", jmse);
    } catch (IOException ioe) {
        log.error("Failed to parse message: {}", ioe);
    } catch (EmailException ee) {
        log.error("Failed to send emails: {}", ee);
    } catch (Exception ex) {
        log.error("Unknown error: {}", ex);
    }
}
Example 65
Project: Activiti-master  File: MailActivityBehavior.java View source code
@Override
public void execute(ActivityExecution execution) {
    boolean doIgnoreException = Boolean.parseBoolean(getStringFromField(ignoreException, execution));
    String exceptionVariable = getStringFromField(exceptionVariableName, execution);
    Email email = null;
    try {
        String toStr = getStringFromField(to, execution);
        String fromStr = getStringFromField(from, execution);
        String ccStr = getStringFromField(cc, execution);
        String bccStr = getStringFromField(bcc, execution);
        String subjectStr = getStringFromField(subject, execution);
        String textStr = textVar == null ? getStringFromField(text, execution) : getStringFromField(getExpression(execution, textVar), execution);
        String htmlStr = htmlVar == null ? getStringFromField(html, execution) : getStringFromField(getExpression(execution, htmlVar), execution);
        String charSetStr = getStringFromField(charset, execution);
        List<File> files = new LinkedList<File>();
        List<DataSource> dataSources = new LinkedList<DataSource>();
        getFilesFromFields(attachments, execution, files, dataSources);
        email = createEmail(textStr, htmlStr, attachmentsExist(files, dataSources));
        addTo(email, toStr);
        setFrom(email, fromStr, execution.getTenantId());
        addCc(email, ccStr);
        addBcc(email, bccStr);
        setSubject(email, subjectStr);
        setMailServerProperties(email, execution.getTenantId());
        setCharset(email, charSetStr);
        attach(email, files, dataSources);
        email.send();
    } catch (ActivitiException e) {
        handleException(execution, e.getMessage(), e, doIgnoreException, exceptionVariable);
    } catch (EmailException e) {
        handleException(execution, "Could not send e-mail in execution " + execution.getId(), e, doIgnoreException, exceptionVariable);
    }
    leave(execution);
}
Example 66
Project: HippoWeblog-master  File: Detail.java View source code
/**
     * <p>Sends mail notification for newly added comment.</p>
     * <p>If component configuration for <code>receiver.email</code> is missing, no mails will be sent.</p>
     * @param commentBean {@link CommentBean}
     * @param request {@link HstRequest}
     */
protected void sendNotificationMail(final CommentBean commentBean, final HstRequest request) {
    String mailhost = getParameter(Email.MAIL_HOST, request);
    String senderEmail = getParameter(Email.SENDER_EMAIL, request);
    String receiverEmail = getParameter(Email.RECEIVER_EMAIL, request);
    if (StringUtils.isBlank(mailhost)) {
        log.info("No value for mail.smtp.host in component configuration, trying localhost");
        mailhost = LOCALHOST;
    }
    if (StringUtils.isBlank(senderEmail)) {
        log.info("No value for sender.email in component configuration, trying noreply@example.com");
        senderEmail = DEFAULT_SENDER_MAIL;
    }
    if (StringUtils.isBlank(receiverEmail)) {
        log.warn("No value for receiver.email in component configuration. Will not try to send mail notification.");
        return;
    }
    SimpleEmail email = new SimpleEmail();
    StringBuffer subject = new StringBuffer("New comment: ");
    subject.append(commentBean.getTitle());
    StringBuffer msg = new StringBuffer("The following comment has been added:\n");
    msg.append(commentBean.getSummary());
    email.setHostName(mailhost);
    try {
        email.addTo(receiverEmail);
        email.setFrom(senderEmail);
        email.setSubject(subject.toString());
        email.setMsg(msg.toString());
        email.send();
    } catch (EmailException e) {
        log.error("Error sending notification for added comment", e);
    }
}
Example 67
Project: SutemaBurstStream-master  File: SutemaBurstStreamMain.java View source code
public static void sendMail(MailConf mailConf, String mailLine) throws EmailException {
    Email email = new SimpleEmail();
    email.setHostName(mailConf.getSmtp_server());
    email.setSmtpPort(mailConf.getSmtp_port());
    email.setAuthenticator(new DefaultAuthenticator(mailConf.getUser_name(), mailConf.getPassword()));
    email.setSSLOnConnect(mailConf.isSmtp_ssl_flag());
    email.setFrom(mailConf.getSrc_mail_adress());
    email.setSubject(Constant.SOFTWARE_NAME + " " + System.currentTimeMillis());
    email.setContent(mailLine, "text/plain; charset=ISO-2022-JP");
    email.setCharset("ISO-2022-JP");
    //			try {
    //				email.setMsg(new String(mailLine.getBytes("iso-2022-jp")));
    //			} catch (UnsupportedEncodingException e) {
    //				// TODO 自動生��れ� catch ブロック
    //				e.printStackTrace();
    //			}
    email.addTo(mailConf.getDest_mail_adress());
    email.send();
}
Example 68
Project: MuninMX-master  File: Methods.java View source code
private static void sendMail(String title, String message, String emailaddy) {
    try {
        Email email = new SimpleEmail();
        email.setHostName(p.getProperty("mailserver.host"));
        email.setSmtpPort(Integer.parseInt(p.getProperty("mailserver.port")));
        if (p.getProperty("mailserver.useauth").equals("true")) {
            email.setAuthentication(p.getProperty("mailserver.user"), p.getProperty("mailserver.pass"));
        }
        if (p.getProperty("mailserver.usessl").equals("true")) {
            email.setSSLOnConnect(true);
        } else {
            email.setSSLOnConnect(false);
        }
        email.setFrom(p.getProperty("mailserver.from"));
        email.setSubject("[MuninMX] " + title);
        email.setMsg(message);
        email.addTo(emailaddy);
        email.send();
    } catch (Exception ex) {
        logger.warn("Unable to send Mail: " + ex.getLocalizedMessage());
    }
}
Example 69
Project: pi4j-javaone-demos-master  File: AccessControl.java View source code
/**
     * Send email message for external notifications
     *
     * @param subject Email Subject Text
     * @param message Email Message Text
     */
private static void sendEmail(String subject, String message) {
    try {
        if (EMAIL_ENABLED && EMAIL_FROM != null && !EMAIL_FROM.isEmpty()) {
            Email email = new SimpleEmail();
            email.setHostName(EMAIL_SERVER);
            email.setSmtpPort(EMAIL_PORT);
            email.setFrom(EMAIL_FROM);
            email.addTo(EMAIL_TO);
            email.setSubject(subject);
            email.setMsg(message);
            email.send();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Example 70
Project: imoten-im-kayac-master  File: MyHtmlEmail.java View source code
/**
     * Set the message.
     *
     * <p>This method overrides {@link MultiPartEmail#setMsg(String)} in
     * order to send an HTML message instead of a plain text message in
     * the mail body. The message is formatted in HTML for the HTML
     * part of the message; it is left as is in the alternate text
     * part.
     *
     * @param msg the message text to use
     * @return this <code>HtmlEmail</code>
     * @throws EmailException if msg is null or empty;
     * see javax.mail.internet.MimeBodyPart for definitions
     * @since 1.0
     */
public Email setMsg(String msg) throws EmailException {
    if (StringUtils.isEmpty(msg)) {
        throw new EmailException("Invalid message supplied");
    }
    setTextMsg(msg);
    StringBuffer htmlMsgBuf = new StringBuffer(msg.length() + HTML_MESSAGE_START.length() + HTML_MESSAGE_END.length());
    htmlMsgBuf.append(HTML_MESSAGE_START).append(msg).append(HTML_MESSAGE_END);
    setHtmlMsg(htmlMsgBuf.toString());
    return this;
}
Example 71
Project: imoten-yuba-master  File: MyHtmlEmail.java View source code
/**
     * Set the message.
     *
     * <p>This method overrides {@link MultiPartEmail#setMsg(String)} in
     * order to send an HTML message instead of a plain text message in
     * the mail body. The message is formatted in HTML for the HTML
     * part of the message; it is left as is in the alternate text
     * part.
     *
     * @param msg the message text to use
     * @return this <code>HtmlEmail</code>
     * @throws EmailException if msg is null or empty;
     * see javax.mail.internet.MimeBodyPart for definitions
     * @since 1.0
     */
public Email setMsg(String msg) throws EmailException {
    if (StringUtils.isEmpty(msg)) {
        throw new EmailException("Invalid message supplied");
    }
    setTextMsg(msg);
    StringBuffer htmlMsgBuf = new StringBuffer(msg.length() + HTML_MESSAGE_START.length() + HTML_MESSAGE_END.length());
    htmlMsgBuf.append(HTML_MESSAGE_START).append(msg).append(HTML_MESSAGE_END);
    setHtmlMsg(htmlMsgBuf.toString());
    return this;
}
Example 72
Project: lab-master  File: MailService.java View source code
public void send(final IMessage message) {
    try {
        Email mail = MailFactory.create(message);
        mail.send();
    } catch (Exception e) {
        throw new MailException(e.getMessage(), e);
    }
}
Example 73
Project: jopenpec-master  File: SimplePECMail.java View source code
@Override
public Email addBcc(String email, String name) throws EmailException {
    throw new EmailException("PEC non consente invii in Bcc");
}
Example 74
Project: batchers-master  File: EmailSenderServiceTest.java View source code
@Test
public void givenAnEmailTO_whenSendingAnEmail_thenTheCorrectDataIsUsedAndTheEmailIsSent() throws Exception {
    EmailSenderService.EmailMapper emailMapper = new EmailSenderService.EmailMapper();
    Email email = emailMapper.mapFromEmailTO(emailTO());
    assertionsForEmail(email, emailTO());
}
Example 75
Project: jphp-master  File: PEmailBackend.java View source code
public void _apply(Email email) throws EmailException {
    email.setMailSession(helper.getMailSession());
}
Example 76
Project: sonarqube-master  File: EmailNotificationChannel.java View source code
private EmailMessage format(Notification notification) {
    for (EmailTemplate template : templates) {
        EmailMessage email = template.format(notification);
        if (email != null) {
            return email;
        }
    }
    LOG.warn("Email template not found for notification: {}", notification);
    return null;
}