<commit_before>/*
 * Copyright (c) 2008 Haulmont Technology Ltd. All Rights Reserved.
 * Haulmont Technology proprietary and confidential.
 * Use is subject to license terms.

 * Author: <NAME>
 * Created: 18.05.2009 11:03:34
 *
 * $Id$
 */
package com.haulmont.cuba.core.app;

import com.haulmont.cuba.core.*;
import com.haulmont.cuba.core.entity.SendingAttachment;
import com.haulmont.cuba.core.entity.SendingMessage;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.core.sys.AppContext;
import com.haulmont.cuba.security.global.LoginException;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.QCodec;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.javamail.JavaMailSender;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.annotation.ManagedBean;
import javax.inject.Inject;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * Emailer MBean implementation.
 * <p/>
 * Provides email functionality, allows to set some emailing parameters through JMX-console.
 */
@ManagedBean(EmailerAPI.NAME)
public class Emailer extends ManagementBean implements EmailerMBean, EmailerAPI {

    private Log log = LogFactory.getLog(Emailer.class);

    private JavaMailSender mailSender;

    private EmailerConfig config;

    @Inject
    private EmailManagerAPI emailManager;

    private static final String EMAIL_SMTP_HOST_PROPERTY_NAME = "cuba.email.smtpHost";
    private static final String EMAIL_DEFAULT_FROM_ADDRESS_PROPERTY_NAME = "cuba.email.fromAddress";

    @Inject
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Inject
    public void setConfig(ConfigProvider configProvider) {
        this.config = configProvider.doGetConfig(EmailerConfig.class);
    }

    @Deprecated
    public EmailerAPI getAPI() {
        return this;
    }

    public void sendEmail(EmailInfo info) throws EmailException {
        sendEmail(info, true);
    }

    public void sendEmail(EmailInfo info, boolean sync) throws EmailException {
        if (info.getTemplatePath() != null) {
            Map map = info.getTemplateParameters() == null ? Collections.EMPTY_MAP : info.getTemplateParameters();
            info.setBody(TemplateHelper.processTemplateFromFile(info.getTemplatePath(), map));
        }
        if (sync) {
            sendEmail(info.getAddresses(), info.getCaption(), info.getBody(), info.getFrom() != null ? info.getFrom() : config.getFromAddress(), info.getAttachment());
        } else {
            sendEmailAsync(info, null, null);
        }
    }


    public void sendEmailAsync(EmailInfo info, Integer attemptsCount, Date deadline) throws EmailException {
        List<SendingMessage> sendingMessageList = splitEmail(info);
        emailManager.addEmailsToQueue(sendingMessageList);
    }


    public void scheduledSendEmail(SendingMessage sendingMessage) throws LoginException, EmailException {
        loginOnce();
        sendEmail(sendingMessage);
    }

    private List<SendingMessage> splitEmail(EmailInfo info) {
        List<SendingMessage> sendingMessageList = new LinkedList<SendingMessage>();
        String[] addrArr = info.getAddresses().split("[,;]");
        for (String addr : addrArr) {
            try {
                addr = addr.trim();
                String fromEmail;
                if (info.getFrom() == null) {
                    fromEmail = config.getFromAddress();
                } else {
                    fromEmail = info.getFrom();
                }
                SendingMessage sendingMessage = createSendingMessage(addr, fromEmail, info.getCaption(), info.getBody(), info.getAttachment());
                sendingMessageList.add(sendingMessage);
            } catch (Exception e) {
                log.error("Exception while creating SendingMessage:" + ExceptionUtils.getStackTrace(e));
            }
        }
        return sendingMessageList;
    }

    public void sendEmail(String addresses, String caption, String body, EmailAttachment... attachment)
            throws EmailException {
        sendEmail(addresses, caption, body, config.getFromAddress(), attachment);
    }

    public void sendEmail(SendingMessage sendingMessage)
            throws EmailException {
        try {
            String addr = sendingMessage.getAddress().trim();
            String fromEmail;
            if (sendingMessage.getFrom() == null) {
                fromEmail = config.getFromAddress();
            } else {
                fromEmail = sendingMessage.getFrom();
            }
//            updateSendingMessageStatus(sendingMessage, SendingStatus.SENDING);
            MimeMessage message = createMessage(addr, sendingMessage.getCaption(), sendingMessage.getContentText(), getEmailAttachments(sendingMessage), fromEmail);
            send(addr, message);

            log.info("Email '" + sendingMessage.getCaption() + "' to '" + addr + "' sent succesfully");
            updateSendingMessageStatus(sendingMessage, SendingStatus.SENT);
        } catch (MessagingException e) {
            log.warn("Unable to send email to '" + sendingMessage.getAddress() + "'", e);
            updateSendingMessageStatus(sendingMessage, SendingStatus.QUEUE);
        } catch (Exception e) {
            log.warn("Unable to send email to '" + sendingMessage.getAddress() + "'", e);
            updateSendingMessageStatus(sendingMessage, SendingStatus.QUEUE);
        }
    }


    public void sendEmail(String addresses, String caption, String body, String from, EmailAttachment... attachment)
            throws EmailException {
        String[] addrArr = addresses.split("[,;]");

        List<String> failedAddresses = new ArrayList<String>();
        List<String> errorMessages = new ArrayList<String>();

        for (String addr : addrArr) {
            SendingMessage sendingMessage = null;
            try {
                addr = addr.trim();
                String fromEmail;
                if (from == null) {
                    fromEmail = config.getFromAddress();
                } else {
                    fromEmail = from;
                }
                sendingMessage = storeMessage(addr, fromEmail, caption, body, attachment, SendingStatus.SENDING);
                MimeMessage message = createMessage(addr, caption, body, attachment, fromEmail);
                send(addr, message);

                log.info("Email '" + caption + "' to '" + addr + "' sent succesfully");
                updateSendingMessageStatus(sendingMessage, SendingStatus.SENT);
            } catch (MessagingException e) {
                log.warn("Unable to send email to '" + addr + "'", e);
                failedAddresses.add(addr);
                errorMessages.add(e.getMessage());
                if (sendingMessage != null)<commit_msg>Emailer bugfix. "From Address" at first is taken from app.properties and only then from database config<commit_after>/*
 * Copyright (c) 2008 Haulmont Technology Ltd. All Rights Reserved.
 * Haulmont Technology proprietary and confidential.
 * Use is subject to license terms.

 * Author: <NAME>
 * Created: 18.05.2009 11:03:34
 *
 * $Id$
 */
package com.haulmont.cuba.core.app;

import com.haulmont.cuba.core.*;
import com.haulmont.cuba.core.entity.SendingAttachment;
import com.haulmont.cuba.core.entity.SendingMessage;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.core.sys.AppContext;
import com.haulmont.cuba.security.global.LoginException;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.QCodec;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.javamail.JavaMailSender;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.annotation.ManagedBean;
import javax.inject.Inject;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * Emailer MBean implementation.
 * <p/>
 * Provides email functionality, allows to set some emailing parameters through JMX-console.
 */
@ManagedBean(EmailerAPI.NAME)
public class Emailer extends ManagementBean implements EmailerMBean, EmailerAPI {

    private Log log = LogFactory.getLog(Emailer.class);

    private JavaMailSender mailSender;

    private EmailerConfig config;

    @Inject
    private EmailManagerAPI emailManager;

    private static final String EMAIL_SMTP_HOST_PROPERTY_NAME = "cuba.email.smtpHost";
    private static final String EMAIL_DEFAULT_FROM_ADDRESS_PROPERTY_NAME = "cuba.email.fromAddress";

    @Inject
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Inject
    public void setConfig(ConfigProvider configProvider) {
        this.config = configProvider.doGetConfig(EmailerConfig.class);
    }

    @Deprecated
    public EmailerAPI getAPI() {
        return this;
    }

    public void sendEmail(EmailInfo info) throws EmailException {
        sendEmail(info, true);
    }

    public void sendEmail(EmailInfo info, boolean sync) throws EmailException {
        if (info.getTemplatePath() != null) {
            Map map = info.getTemplateParameters() == null ? Collections.EMPTY_MAP : info.getTemplateParameters();
            info.setBody(TemplateHelper.processTemplateFromFile(info.getTemplatePath(), map));
        }
        if (sync) {
            sendEmail(info.getAddresses(), info.getCaption(), info.getBody(), info.getFrom() != null ? info.getFrom() : getFromAddress(), info.getAttachment());
        } else {
            sendEmailAsync(info, null, null);
        }
    }


    public void sendEmailAsync(EmailInfo info, Integer attemptsCount, Date deadline) throws EmailException {
        List<SendingMessage> sendingMessageList = splitEmail(info);
        emailManager.addEmailsToQueue(sendingMessageList);
    }


    public void scheduledSendEmail(SendingMessage sendingMessage) throws LoginException, EmailException {
        loginOnce();
        sendEmail(sendingMessage);
    }

    private List<SendingMessage> splitEmail(EmailInfo info) {
        List<SendingMessage> sendingMessageList = new LinkedList<SendingMessage>();
        String[] addrArr = info.getAddresses().split("[,;]");
        for (String addr : addrArr) {
            try {
                addr = addr.trim();
                String fromEmail;
                if (info.getFrom() == null) {
                    fromEmail = getFromAddress();
                } else {
                    fromEmail = info.getFrom();
                }
                SendingMessage sendingMessage = createSendingMessage(addr, fromEmail, info.getCaption(), info.getBody(), info.getAttachment());
                sendingMessageList.add(sendingMessage);
            } catch (Exception e) {
                log.error("Exception while creating SendingMessage:" + ExceptionUtils.getStackTrace(e));
            }
        }
        return sendingMessageList;
    }

    public void sendEmail(String addresses, String caption, String body, EmailAttachment... attachment)
            throws EmailException {
        sendEmail(addresses, caption, body, getFromAddress(), attachment);
    }

    public void sendEmail(SendingMessage sendingMessage)
            throws EmailException {
        try {
            String addr = sendingMessage.getAddress().trim();
            String fromEmail;
            if (sendingMessage.getFrom() == null) {
                fromEmail = getFromAddress();
            } else {
                fromEmail = sendingMessage.getFrom();
            }
//            updateSendingMessageStatus(sendingMessage, SendingStatus.SENDING);
            MimeMessage message = createMessage(addr, sendingMessage.getCaption(), sendingMessage.getContentText(), getEmailAttachments(sendingMessage), fromEmail);
            send(addr, message);

            log.info("Email '" + sendingMessage.getCaption() + "' to '" + addr + "' sent succesfully");
            updateSendingMessageStatus(sendingMessage, SendingStatus.SENT);
        } catch (MessagingException e) {
            log.warn("Unable to send email to '" + sendingMessage.getAddress() + "'", e);
            updateSendingMessageStatus(sendingMessage, SendingStatus.QUEUE);
        } catch (Exception e) {
            log.warn("Unable to send email to '" + sendingMessage.getAddress() + "'", e);
            updateSendingMessageStatus(sendingMessage, SendingStatus.QUEUE);
        }
    }


    public void sendEmail(String addresses, String caption, String body, String from, EmailAttachment... attachment)
            throws EmailException {
        String[] addrArr = addresses.split("[,;]");

        List<String> failedAddresses = new ArrayList<String>();
        List<String> errorMessages = new ArrayList<String>();

        for (String addr : addrArr) {
            SendingMessage sendingMessage = null;
            try {
                addr = addr.trim();
                String fromEmail;
                if (from == null) {
                    fromEmail = getFromAddress();
                } else {
                    fromEmail = from;
                }
                sendingMessage = storeMessage(addr, fromEmail, caption, body, attachment, SendingStatus.SENDING);
                MimeMessage message = createMessage(addr, caption, body, attachment, fromEmail);
                send(addr, message);

                log.info("Email '" + caption + "' to '" + addr + "' sent succesfully");
                updateSendingMessageStatus(sendingMessage, SendingStatus.SENT);
            } catch (MessagingException e) {
                log.warn("Unable to send email to '" + addr + "'", e);
                failedAddresses.add(addr);
                errorMessages.add(e.getMessage());
                if (sendingMessage != null)
{'fraction_non_alphanumeric': 0.10158013544018059, 'fraction_numerical': 0.002462548737943772, 'mean_word_length': 2.8122555410691006, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4889321', 'n_tokens_mistral': 3893, 'n_tokens_neox': 3759, 'n_words': 868}