【问题标题】:Email Sender Freezes电子邮件发件人冻结
【发布时间】:2011-09-04 03:03:48
【问题描述】:

我制作了一个应用程序,它可以压缩一些文件并通过电子邮件发送它们。大约有 70 个文件(它们的总大小约为 800kb)。

压缩过程冻结了我的应用程序(但没关系,因为它需要大约一秒钟)

问题在于电子邮件流程。调试的时候发现整个邮件准备过程还是蛮快的,除了

smtp.Send(消息)

这完全冻结了我的应用程序:5 秒后,应用程序仍在运行,但从任务栏中消失,即使在发送电子邮件后,应用程序仍然没有响应。

发送邮件功能:

    public void SendMail(string FromGmailEmail, string GmailPassword, string ToEmail, string Subject, string Body, string[] AttachmentsPaths)
    {
        var fromAddress = new MailAddress(FromGmailEmail, "None");
        var toAddress = new MailAddress(ToEmail, "None");
        string fromPassword = GmailPassword;
        string subject = Subject;
        string body = Body;

        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
        };
        var message = new MailMessage(fromAddress, toAddress);
        message.Subject = subject;
        message.Body = body;

        try
        {
            for (int i = 0; i < AttachmentsPaths.Length; i++)
                message.Attachments.Add(new Attachment(AttachmentsPaths[i]));
        }
        catch (FileNotFoundException)
        {
        }
        smtp.Timeout = int.MaxValue;
        smtp.Send(message);
    }

我在发送电子邮件时打开了一个新线程。

public void OpenEmailThread(string FromGmailEmail, string GmailPassword, string ToEmail, string Subject, string Body, string[] AttachmentsPaths)
    {
        Thread thread = new Thread(() => SendMail(FromGmailEmail, GmailPassword, ToEmail, Subject, Body, AttachmentsPaths));
        thread.Name = "EmailThread";
        thread.Start();
    }

旁注:有些输出告诉我:

在 mscorlib.dll 中发生了“System.IO.IOException”类型的第一次机会异常

smtp.Send(消息)

(但这是我最小的问题)

编辑:原来我正在编辑一个文件,而他正在发送它。我知道它会发生,这就是为什么我添加了一个名为“IsEmailing”的布尔变量来在我发送电子邮件时锁定文件。原来文件仍在“smtp.Send(message);”之后上传。

解决方案:在发送之前和仅在发送之前压缩附件。这样,zip 只会出现一次,因此无法修改 .zip 文件。

【问题讨论】:

  • 购买更好的互联网服务或使用BackgroundWorker。

标签: c# multithreading email smtp ioexception


【解决方案1】:

我用它在一个新线程上发送邮件,它工作正常...

        public void SendEmail(string from, string to, string subject, string body, string attachPath)
    {
        Thread threadSendMails;
        threadSendMails = new Thread(delegate()
        {

            sendEmail(from, to, subject, body, attachPath);

        });

        threadSendMails.IsBackground = true;
        threadSendMails.Start();

    }

其中 sendMail 是我自己的邮件功能。

【讨论】:

  • 我尝试添加“thread.IsBackground = true”,但没有帮助,您可以发布您的 sendMail 功能吗?
  • 尝试打开一个新项目并发送电子邮件,它工作正常。谢谢。
  • 不,谢谢。 (原来我的错误是我在他发送时添加了一个文件)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 2016-01-21
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多