电子邮件发件人冻结

时间:2011-05-28 23:10:09

标签: c# multithreading email smtp ioexception

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

zip进程会冻结我的应用程序(但它可以,因为它需要大约一秒钟)

问题在于电子邮件流程。在调试时,我发现整个电子邮件准备过程非常快,除了

  

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'类型的第一次机会异常

on

  

smtp.Send(消息)

(但这是我遇到的最少的问题)

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

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

1 个答案:

答案 0 :(得分: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是我自己的邮件功能。

相关问题