通过 C# 通过 Outlook 2010 发送电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19911230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:06:24  来源:igfitidea点击:

Sending Email through Outlook 2010 via C#

c#emailreferenceoutlookoffice-2010

提问by SteveAnselment

I am trying to send an email from inside my C# console App. I have added the references and using statements but it seems I have not added everything I need. This is the first time I have ever attempted to do this so I figure there is something I have forgotten.

我正在尝试从我的 C# 控制台应用程序内部发送电子邮件。我已经添加了引用和使用语句,但似乎我没有添加我需要的一切。这是我第一次尝试这样做,所以我想我已经忘记了一些事情。

I got this code snippet from the MSDN site http://msdn.microsoft.com/en-us/library/vstudio/ms269113(v=vs.100).aspx

我从 MSDN 站点http://msdn.microsoft.com/en-us/library/vstudio/ms269113(v=vs.100).aspx得到了这个代码片段

ScreenShot of code from VS2010 showing the build errors

来自 VS2010 的代码屏幕截图,显示了构建错误

Here is the code that I am getting issues with in VS 2010

这是我在 VS 2010 中遇到问题的代码

using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Runtime.InteropServices;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

namespace FileOrganizer
{
    class Program
    {
        private void CreateMailItem()
        {
            //Outlook.MailItem mailItem = (Outlook.MailItem)
            // this.Application.CreateItem(Outlook.OlItemType.olMailItem);
            Outlook.Application app = new Outlook.Application();
            Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem);
            mailItem.Subject = "This is the subject";
            mailItem.To = "[email protected]";
            mailItem.Body = "This is the message.";
            mailItem.Attachments.Add(logPath);//logPath is a string holding path to the log.txt file
            mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
            mailItem.Display(false);
        }
    }
}

采纳答案by Marvin Smit

replace the line

更换线

Outlook.MailItem mailItem = (Outlook.MailItem)
this.Application.CreateItem(Outlook.OlItemType.olMailItem);

with

Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

Hope this helps,

希望这可以帮助,

回答by c00000fd

This is how you can send an email via Microsoft Office Outlook. In my case I was using Office 2010, but I suppose it should work with newer versions.

这是您可以通过 Microsoft Office Outlook 发送电子邮件的方式。就我而言,我使用的是 Office 2010,但我认为它应该适用于较新的版本。

The upvoted sample above just displays the message. It does not send it out. Moreover it doesn't compile.

上面的 upvoted 示例只显示消息。它不发送它。而且它不编译。

So first you need to add these references to your .NETproject:

所以首先你需要将这些引用添加到你的.NET项目中:

enter image description here

在此处输入图片说明

Like I said in my comment to his OP:

就像我在对他的 OP 的评论中所说的那样:

You will need to add the following references: (1) From .NET tab add Microsoft.Office.Tools.Outlook for runtime v.4.0.*, then (2) again from .NET tab add Microsoft.Office.Interop.Outlook for version 14.0.0.0 in my case, and (3) COM object Microsoft Office 12.0 Object Library for Microsoft.Office.Core.

您将需要添加以下引用:(1) 从 .NET 选项卡添加 Microsoft.Office.Tools.Outlook for runtime v.4.0.*,然后 (2) 再次从 .NET 选项卡添加 Microsoft.Office.Interop.Outlook for在我的情况下是 14.0.0.0 版,以及 (3) Microsoft.Office.Core 的 COM 对象 Microsoft Office 12.0 对象库。

Then here's the code to send out emails:

然后这里是发送电子邮件的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Configuration;
using System.IO;
using System.Net.Mail;
using System.Runtime.InteropServices;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

public enum BodyType
{
    PlainText,
    RTF,
    HTML
}

    //....

    public static bool sendEmailViaOutlook(string sFromAddress, string sToAddress, string sCc, string sSubject, string sBody, BodyType bodyType, List<string> arrAttachments = null, string sBcc = null)
    {
        //Send email via Office Outlook 2010
        //'sFromAddress' = email address sending from (ex: "[email protected]") -- this account must exist in Outlook. Only one email address is allowed!
        //'sToAddress' = email address sending to. Can be multiple. In that case separate with semicolons or commas. (ex: "[email protected]", or "[email protected]; [email protected]")
        //'sCc' = email address sending to as Carbon Copy option. Can be multiple. In that case separate with semicolons or commas. (ex: "[email protected]", or "[email protected]; [email protected]")
        //'sSubject' = email subject as plain text
        //'sBody' = email body. Type of data depends on 'bodyType'
        //'bodyType' = type of text in 'sBody': plain text, HTML or RTF
        //'arrAttachments' = if not null, must be a list of absolute file paths to attach to the email
        //'sBcc' = single email address to use as a Blind Carbon Copy, or null not to use
        //RETURN:
        //      = true if success
        bool bRes = false;

        try
        {
            //Get Outlook COM objects
            Outlook.Application app = new Outlook.Application();
            Outlook.MailItem newMail = (Outlook.MailItem)app.CreateItem(Outlook.OlItemType.olMailItem);

            //Parse 'sToAddress'
            if (!string.IsNullOrWhiteSpace(sToAddress))
            {
                string[] arrAddTos = sToAddress.Split(new char[] { ';', ',' });
                foreach (string strAddr in arrAddTos)
                {
                    if (!string.IsNullOrWhiteSpace(strAddr) &&
                        strAddr.IndexOf('@') != -1)
                    {
                        newMail.Recipients.Add(strAddr.Trim());
                    }
                    else
                        throw new Exception("Bad to-address: " + sToAddress);
                }
            }
            else
                throw new Exception("Must specify to-address");

            //Parse 'sCc'
            if (!string.IsNullOrWhiteSpace(sCc))
            {
                string[] arrAddTos = sCc.Split(new char[] { ';', ',' });
                foreach (string strAddr in arrAddTos)
                {
                    if (!string.IsNullOrWhiteSpace(strAddr) &&
                        strAddr.IndexOf('@') != -1)
                    {
                        newMail.Recipients.Add(strAddr.Trim());
                    }
                    else
                        throw new Exception("Bad CC-address: " + sCc);
                }
            }

            //Is BCC empty?
            if (!string.IsNullOrWhiteSpace(sBcc))
            {
                newMail.BCC = sBcc.Trim();
            }

            //Resolve all recepients
            if (!newMail.Recipients.ResolveAll())
            {
                throw new Exception("Failed to resolve all recipients: " + sToAddress + ";" + sCc);
            }


            //Set type of message
            switch (bodyType)
            {
                case BodyType.HTML:
                    newMail.HTMLBody = sBody;
                    break;
                case BodyType.RTF:
                    newMail.RTFBody = sBody;
                    break;
                case BodyType.PlainText:
                    newMail.Body = sBody;
                    break;
                default:
                    throw new Exception("Bad email body type: " + bodyType);
            }


            if (arrAttachments != null)
            {
                //Add attachments
                foreach (string strPath in arrAttachments)
                {
                    if (File.Exists(strPath))
                    {
                        newMail.Attachments.Add(strPath);
                    }
                    else
                        throw new Exception("Attachment file is not found: \"" + strPath + "\"");
                }
            }

            //Add subject
            if(!string.IsNullOrWhiteSpace(sSubject))
                newMail.Subject = sSubject;

            Outlook.Accounts accounts = app.Session.Accounts;
            Outlook.Account acc = null;

            //Look for our account in the Outlook
            foreach (Outlook.Account account in accounts)
            {
                if (account.SmtpAddress.Equals(sFromAddress, StringComparison.CurrentCultureIgnoreCase))
                {
                    //Use it
                    acc = account;
                    break;
                }
            }

            //Did we get the account
            if (acc != null)
            {
                //Use this account to send the e-mail. 
                newMail.SendUsingAccount = acc;

                //And send it
                ((Outlook._MailItem)newMail).Send();

                //Done
                bRes = true;
            }
            else
            {
                throw new Exception("Account does not exist in Outlook: " + sFromAddress);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("ERROR: Failed to send mail: " + ex.Message);
        }

        return bRes;
    }

And here's how you'd use it:

这是你如何使用它:

List<string> arrAttachFiles = new List<string>() { @"C:\Users\User\Desktop\Picture.png" };

bool bRes = sendEmailViaOutlook("[email protected]",
    "[email protected], [email protected]", null,
    "Test email from script - " + DateTime.Now.ToString(),
    "My message body - " + DateTime.Now.ToString(),
    BodyType.PlainText,
    arrAttachFiles,
    null);

回答by Ashutosh Vishwakarma

You need to cast the
app.CreateItem(Outlook.OlItemType.olMailItem)
object in
Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem)
to
Outlook.MailItemtype
since no implicit casting is available.

您需要将
app.CreateItem(Outlook.OlItemType.olMailItem)
对象转换
Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem)

Outlook.MailItem类型,
因为没有可用的隐式转换。

Replace

代替

Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem); 

with

Outlook.MailItem mailItem = (Outlook.MailItem)app.CreateItem(Outlook.OlItemType.olMailItem);