尝试在C#中发送电子邮件时出现InvalidCastException错误

时间:2016-08-05 12:01:59

标签: c# winforms

我想从我的C#(winform)应用程序发送一封电子邮件到地址展望但我在下面的行中遇到错误:

Outlook.MailItem mail =(Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);

我收到以下错误:

  

无法转换类型的COM对象   'Microsoft.Office.Interop.Outlook.ApplicationClass'到接口类型   “Microsoft.Office.Interop.Outlook._Application”。此操作失败   因为QueryInterface调用COM组件的接口   由于IID'{00063001-0000-0000-C000-000000000046}'失败了   以下错误:库未注册。 (例外de HRESULT:   0x80040155)

我的完整代码是:

void SendEmailAuto()
        {
            try
            {
                OpenFileDialog attachment = new OpenFileDialog();
                attachment.Title = "Select a file to send";
                attachment.ShowDialog();
                Outlook._Application _app = new Outlook.Application();
                Outlook.MailItem mail =mail= (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);
                mail.To = 'paul.m@adt.org";
                mail.Subject = "Text";
                mail.Body = "Funding Request Team";

                if (attachment.FileName.Length > 0)
                {
                    mail.Attachments.Add(attachment.FileName, Outlook.OlAttachmentType.olByValue, 1, attachment.FileName);
                    mail.Importance = Outlook.OlImportance.olImportanceHigh;
                    ((Outlook.MailItem)mail).Send();
                }
                else
                {
                    MessageBox.Show("You are kindly requested to attach a document.", "MISSING FILE", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
        }

1 个答案:

答案 0 :(得分:0)

请检查:http://www.fieldstonsoftware.com/support/support_gsyncit_2013.shtml,这可能是某些注册问题。