当前位置: 首页 > 知识库问答 >
问题:

电子邮件未在@Async注释方法中发送

康照
2023-03-14
    null

所有步骤2、3和4都将在一个带有@async注释的方法中执行。问题是,如果我重新启动后端服务器,只发送一个下载请求,一切都很好,这意味着电子邮件可以收到。但发送更多下载请求后就不起作用了。不会再发送电子邮件。没有错误,没有警告,但所有需要的数据都被正确接收,只是没有电子邮件被发送出去。

有人知道它的问题是什么吗?

我的电子邮件发件人:

public class AbstractEmailSender {

    public MimeMessage mimeMessage;
    public MimeMessageHelper mimeMessageHelper;
    public JavaMailSender javaMailSender;
    private final String SENDER = MY_SEND_EMAIL_ADDRESS;
    public final String USER_NAME_KEY = "username";

    public AbstractEmailSender(JavaMailSender javaMailSender) throws MessagingException {
//        this.javaMailSender = new JavaMailSenderImpl();
        this.javaMailSender = javaMailSender;
        this.doInitialization();
    }

    public void doInitialization() throws MessagingException {
        this.mimeMessage = this.javaMailSender.createMimeMessage();
        this.mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
    }

    public void setEmailContext(String receiver, String subject) throws MessagingException {
        this.mimeMessageHelper.setSubject(subject);
        this.mimeMessageHelper.setFrom(SENDER);
        this.mimeMessageHelper.setTo(receiver);
    }
}

@Component
public class DownloadDataSuccessEmailSender extends AbstractEmailSender implements MailService{

    private final TemplateEngine templateEngine;
    private final static String DOWNLOAD_DATA_SUCCESS_EMAIL_SUBJECT = XXXXXX;
    private final static String SIGNED_URL_KEY = "signedUrl";
    private final static String DOWNLOAD_EMAIL_TEMPLATE_NAME = "downloadDataSuccessEmail.html";
    private static final Logger logger = LogManager.getLogger(DownloadDataSuccessEmailSender.class);


    public DownloadDataSuccessEmailSender(JavaMailSender javaMailSender, TemplateEngine templateEngine) throws MessagingException {
        super(javaMailSender);
        this.templateEngine = templateEngine;
    }

    @Override
    public void sendEmailWithSignedUrlToDownloadFile(URL signedUrl, String username, String receiver) {
        // print the result to make sure all data are processed correctly, nothing wrong with 
        //this step
        System.out.println(signedUrl);
        System.out.println(username);
        System.out.println(receiver);
        try{
            super.setEmailContext(receiver, DOWNLOAD_DATA_SUCCESS_EMAIL_SUBJECT);
            Context context = new Context();
            context.setVariable(this.USER_NAME_KEY, username);
            context.setVariable(SIGNED_URL_KEY, signedUrl);
            String email = this.templateEngine.process(DOWNLOAD_EMAIL_TEMPLATE_NAME, context);
            this.mimeMessageHelper.setText(email, true);
            this.javaMailSender.send(mimeMessage);
        }catch (MailException | MessagingException e) {
            logger.error("Email with download data error: ", e);
            throw new EmailSendException(ErrorInfo.EMAIL_SEND_EXCEPTION.getCode(), ErrorInfo.EMAIL_SEND_EXCEPTION.getMessage());
        }
    }
}

spring:
  mail:
    host: smtp.gmail.com
    username: MY_EMAIL_ADDRESS
    password: MY_PASSWORD
    properties.mail.smtp:
      auth: true
      connectiontimeout: 60000
      timeout: 60000
      writetimeout: 50000
      starttls.enable: true
    port: 587
    protocol: smtp
  thymeleaf:
    prefix: classpath:/templates/
@Override
    @Async
    @Transactional(timeout = DOWNLOAD_DATA_TRANSACTION_TIME_LIMIT)
    public void downloadFile(SearchQuery query, DownloadRequestRecord downloadRecord){
        String username = downloadRecord.getUsername();
        String emailAddress = this.userService.getUserEmailAddressByUsername(username);
        try{
            // here ignore the parts to get data from database and generate zip file and check if the file is uploaded to cloud space successfully here
            // ......
            if (uploadFile == null) { // check if file exists
                logger.error("File: {} does not exist in cloud!", zipFileName);
                downloadRecord.setSuccess(0);
                this.downloadDataFailMessageEmailSender.sendEmailWithDownloadDataFail(emailAddress, username, downloadRecord.getQuery(), downloadRecord.getDownloadTime()); // send email to inform user the download is fail
            } else {
// file exists, generate signed URL and send email with download link
               this.downloadDataSuccessEmailSender.sendEmailWithSignedUrlToDownloadFile(signedUrl, username, emailAddress);
                downloadRecord.setSuccess(1);
            }
        } catch (IOException | EmailSendException ex) {
            logger.error("Exception from downloading data: ", ex);
            downloadRecord.setSuccess(0);
        } finally {
            this.userService.recordDownloadHistoryOfUser(downloadRecord);
        }
    }
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    private static final int CORE_POOL_SIZE = 6;
    private static final int MAX_POOL_SIZE = 10;
    private static final int QUEUE_CAPACITY = 100;
    private static final String THREAD_NAME_PREFIX = "ThreadPoolTaskExecutor-";
    private static final Logger logger = LogManager.getLogger(AsyncConfig.class);

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
                logger.error("ERROR: ", throwable);
            }
        };
    }
}

共有1个答案

艾昊明
2023-03-14

在sendEmailWithSignedUrlToDownloadFile中,使用创建MimeMessage

MimeMessage MimeMessage=MailSender.createMimeMessage();

而不是将MimeMessage的单个实例作为超类的成员

 类似资料:
  • 我使用AWS SES服务发送电子邮件与验证的测试电子邮件地址在SES和使用相同的来源。 我正试图将电子邮件发送到其他电子邮件地址,但无法发送。这是给我的错误“电子邮件地址未经验证。以下身份未通过在US-EAST-1地区的检查”。 发送电子邮件的代码参考:https://aws.amazon.com/premiumsupport/knowledge-center/lambda-send-email-

  • 你好;我正在使用s.o上给出的答案进行smtp邮件;(如果搜索,相信这是第一个结果) 但我仍然没有收到邮件;任何人都可以帮助发现任何错误或提供替代解决方案吗?我已经使用了内置的邮件程序,但它没有被认证,请参阅 -

  • 问题内容: 我最近开始编程我的第一个node.js。但是,我发现我无法创建直接发送到我的电子邮件的“联系我”表单,因为我无法从能够发送电子邮件的节点中找到任何模块。 有人知道node.js电子邮件库或示例联系表单脚本吗? 问题答案: node-email-templates是一个更好的选择:https : //github.com/niftylettuce/node-email- template

  • 我正在尝试用Laravel 5.2发送电子邮件。这是我第一次在拉威尔发电子邮件。但它抛出了这个错误 这是我发送电子邮件的代码: 这是我在env文件中的电子邮件设置 我的欢迎视图只有一条消息“Hello world” 我已经在Gmail设置中为我的电子邮件配置了不太安全的应用程序设置。那么,我的代码有什么问题,为什么会抛出那个错误?

  • 问题内容: 我正在使用sendgrid发送电子邮件,并且使用以下代码可以正常工作,但没有附件。 但是我需要发送附件,因此我搜索了github源和Web文档API,由于某种原因,没有javadocs,但是有一个示例GitHub sendgrid, 所以我一直在尝试直到它起作用为止,我缩小了一些异常和响应代码,起初我是被禁止的未经授权,最好是响应202,表示有效且已排队(在此处检查),这是我的代码发送

  • 这个代码应该发送一封电子邮件到指定的地址,当我硬编码“文本” 努力编码的文本和主题,它发送罚款!注意:使用GMAIL时,您必须启用不太安全的应用程序!