Skip to main content
 首页 » 编程设计

c#之无法通过 C# 从 Outlook 发送邮件

2024年01月28日33飞鱼

我正在尝试向我的同事发送邮件,但在发送第一封邮件后,应用程序崩溃了。我收到这条消息

COMException 未被用户代码处理。 “该项目已被移动或删除。”

private void SendMail() 
{ 
    var usersEmailAddresses = Factory.Users.List(); // .List() lists all the data from the Users table. 
 
    Application OutlookApplication = new Application(); 
    MailItem OutlookMail = (MailItem)OutlookApplication.CreateItem(OlItemType.olMailItem); 
 
    OutlookMail.Subject = @"TEST/Ushqimi i caktuar per sot"; 
 
    MailBody //region, here I assign the MailBody Text. 
 
    for (int index = 0; index < usersEmailAddresses.Count; index++) 
    { 
        OutlookMail.To = usersEmailAddresses[index].Email;  //Here is where I get the exception, AFTER trying to assign the second email. 
 
        if (usersEmailAddresses[index].RecieveEmail && !usersEmailAddresses[index].IsOnVacation) 
        { 
            ((_MailItem)OutlookMail).Send(); 
        } 
    } 
} 

我做错了什么?有什么建议吗?

请您参考如下方法:

MailItem OutlookMail = (MailItem)OutlookApplication.CreateItem(OlItemType.olMailItem); 

您正在循环外创建邮件项目。它需要在循环内创建,因为一旦您发送 OutlookMail 它就不再存在,因此您需要一个新的邮件对象。