Задание на отправку электронной почты с помощью кварца, невозможность Session.getInstance

Я новичок в кварце и javamail, но мне нужно отправить электронное письмо пакетным заданием. Я попытался 1. отправить электронное письмо с одним классом java: успех 2. запустить задание с квартами (только println): успех 3. запустить задание с квартами (для отправки электронной почты): не удалось

это мой класс работы:

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import org.quartz.*;


public class EmailJob implements Job {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            EmailSender es = new EmailSender();
            es.sendBillingEmail();

            System.out.println("Job Email Runnning");
            final String username = "[email protected]";
            final String password = "xxxxxxxxxx";

            Properties props = new Properties();
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.mydomain.com");//smtp.gmail.com
            props.put("mail.smtp.port", "587");//587

            Session session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            System.out.println("Job Email Running 2");
            // Sending email
            try {

                Message message = new MimeMessage(session);

                message.setFrom(new InternetAddress("[email protected]"));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
                message.setSubject("Test Email");
                String body = "Dear Bapak Recipients"
                        + "<br>Just test email";

                message.setContent(body, "text/html; charset=utf-8");
                Transport.send(message);

                System.out.println("Done");

            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


}

результат:

Job Email Running (i got this message in console)
Job Email Running 2 (i code this but didnt see in console, 
         my suspect theres an error when creating session)

кварц.xml

    <?xml version="1.0" encoding="UTF-8"?>
<job-scheduling-data
    xmlns="http://www.quartz-scheduler.org/xml/JobSchedulingData"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.quartz-scheduler.org/xml/JobSchedulingData http://www.quartz-scheduler.org/xml/job_scheduling_data_1_8.xsd"
    version="1.8">  
    <pre-processing-commands>
        <delete-jobs-in-group>*</delete-jobs-in-group>  <!-- clear all jobs in scheduler -->
        <delete-triggers-in-group>*</delete-triggers-in-group> <!-- clear all triggers in scheduler -->
    </pre-processing-commands>
    <processing-directives>
        <overwrite-existing-data>true</overwrite-existing-data>
        <ignore-duplicates>false</ignore-duplicates>
    </processing-directives>
    <schedule>
        <job>
            <name>EmailJob</name>
            <job-class>jobs.EmailJob</job-class>
        </job>
        <trigger>
            <cron>
                <name>EveryWorkDay</name>
                <job-name>EmailJob</job-name>     
                <cron-expression>0 0/2 * 1/1 * ? *</cron-expression><!-- 0 0 20 ? * MON-FRI * -->
            </cron>
        </trigger>
    </schedule>
</job-scheduling-data>

кварц.свойства

# Generic configuration - probably not needed, most of this is just the defaults
org.quartz.scheduler.instanceName = MyScheduler
org.quartz.scheduler.instanceId = 1
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 20
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

# Configure it to look in the quartz.xml for the job schedules
org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin
org.quartz.plugin.jobInitializer.fileNames = quartz.xml
org.quartz.plugin.jobInitializer.failOnFileNotFound = true
org.quartz.plugin.jobInitializer.scanInterval = 120

в консоли нет ошибки. я понятия не имею, где ошибка. Нужна помощь от вас, ребята.


person Daniel Robertus    schedule 17.08.2017    source источник
comment
Вы получаете исключение? Что показывает вывод отладки JavaMail? Обратите внимание, что вы можете упростить свой код, исправив распространенные ошибки JavaMail.   -  person Bill Shannon    schedule 17.08.2017
comment
Привет, Билл, я не получил исключения. Я попытался отправить часть электронной почты другому классу EmailSender, но все та же проблема.. она всегда зависает, когда я вызываю Session.getInstance..   -  person Daniel Robertus    schedule 17.08.2017


Ответы (1)


наконец, это может работать. Я обновил библиотеку до версии Java Mail 1.6.0.. и она работает с тем же кодом. Надеюсь, это поможет другим с той же проблемой, что и я. Вы можете скачать его по этой ссылке:

https://github.com/javaee/javamail/releases

person Daniel Robertus    schedule 17.08.2017