首页 > 解决方案 > 如何使用 Outlook 从 Visual Studio 发送电子邮件?

问题描述

我试图在我的 C# 应用程序中发送一封电子邮件。我添加了引用,我使用了语句,但似乎我没有添加所有内容。

这是代码:

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 = "someone@example.com";
            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);
        }
    }
}

标签: c#visual-studioemailoutlook

解决方案


您可以使用以下代码发送电子邮件:

using Microsoft.Office.Interop.Outlook;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp7
{
    class Program
    {
       static void Main(string[] args)
        {
            Microsoft.Office.Interop.Outlook.Application app;
                try
                {
                    app = (Microsoft.Office.Interop.Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
                }
                catch
                {
                    app = new Microsoft.Office.Interop.Outlook.Application();
                }

                if (app == null)
                {
                    return;
                }
                string stringHtmlBodyfromFile = File.ReadAllText(@"D:\test.html");
                Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem) as
                                                                     Microsoft.Office.Interop.Outlook.MailItem;
                mailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
                mailItem.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh;
                mailItem.Subject = subject;
                mailItem.To = “sendemail address”;
                mailItem.Recipients.Add();
                mailItem.HTMLBody = stringHtmlBodyfromFile;
                mailItem.CC = “ccmailAddress”;

                mailItem.Attachments.Add();

               ((Microsoft.Office.Interop.Outlook._MailItem)mailItem).Send();

        }
   }
}

推荐阅读