【问题标题】:MailMessage sends mail with empty subject and attachmentsMailMessage 发送带有空主题和附件的邮件
【发布时间】:2019-11-08 14:01:40
【问题描述】:

所以我试图通过我的中继 smtp 发送一封带有 html 正文、主题和可选附件的电子邮件。但是,发送工作无一例外,正在发送的邮件以一个空主题结束,并且没有附件,这些附件应该从我的 Web 应用程序的 wwwroot 文件夹中获取文件,该文件夹与我的 API 和控制台应用程序托管在同一域中。将从任务调度程序调用此控制台应用程序。该程序将我的 API 作为依赖项,以便它可以调用 ProcessQueue 任务。这个是从我的控制台应用程序中正确调用的。要获取电子邮件的数据,代码将从 MailQueue 表中检索数据,然后像这样填充邮件消息:

    public async Task ProcessQueue(int range, bool send)
    {
        SmtpClient client = new SmtpClient
        {
            Host = "outbound.domain",
            Port = 587,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential("email@domain.com", "")
        };

        var items = await _context.MailQueues.Take(range).ToListAsync();

        MailMessage message = new MailMessage();

        foreach (var item in items)
        {
            try
            {
                message.From = new MailAddress(item.From);
                message.Subject = item.Subject; // The subject is being filled correctly in my situation, but when the email arrives it isn't
                message.IsBodyHtml = true;
                message.To.Add(item.To);
                message.Body = item.Content;
                if (send)
                {
                    AddAttachments(message, item.Docs);
                    client.Send(message);
                    _context.MailQueues.Remove(item);
                    message.To.Clear();
                }
            }
            catch(Exception ex)
            {
                item.Exception = ex.ToString();
                _context.Entry(item).State = System.Data.Entity.EntityState.Modified;
            }
        }

附件方法:

    private void AddAttachments(MailMessage message, string docs)
    {
        if (docs != null)
        {
            List<string> list = JsonConvert.DeserializeObject<List<string>>(docs);
            foreach (string item2 in list)
            {
                Attachment item = new Attachment(HttpContext.Current.Server.MapPath("/wwwroot/documents/") + item2)
                {
                    Name = item2
                };
                message.Attachments.Add(item);
            }
        }
    }

我的域名结构:

domain.com > webappplicatie(包含我的网络应用程序及其 wwwroot 文件夹)

domain.com > webapi(包含我的 web api)

domain.com > mailqueuer(我的控制台应用程序的位置)

我的目标是发送带有可选附件的邮件,这些附件位于网络应用程序的 wwwroot 文件夹及其主题中。 MailQueue 对象的所有数据都填满了!但我仍然遇到这个问题。

有人知道解决办法吗?

【问题讨论】:

  • 不捕获并吞下异常,看看会发生什么异常?
  • 我可以试试,但是如果有异常应该在数据库中显示,我现在就试试你的建议
  • 正如我所说,没有例外
  • 首先将MailMessage message = new MailMessage(); 放入循环而不是外部。也许有帮助。
  • 我做了,还是一样。是否可能与发件人地址和/或垃圾邮件文件夹有关?

标签: c# asp.net


【解决方案1】:

我通过将 MailQueue 的数据库和 smtp 逻辑放入控制台应用程序解决了这个问题。我不完全知道为什么我的问题不起作用,但我愿意接受答案和建议!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-15
    • 2020-11-06
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    相关资源
    最近更新 更多