Отправка электронной почты через Outlook 2010 через С#

Я пытаюсь отправить электронное письмо из моего приложения консоли С#. Я добавил ссылки и использовал заявления, но, похоже, я не добавил все, что мне нужно. Это первый раз, когда я когда-либо пытался сделать это, поэтому считаю, что я забыл.

Я получил этот фрагмент кода с сайта MSDN http://msdn.microsoft.com/en-us/library/vstudio/ms269113(v=vs.100).aspx

ScreenShot of code from VS2010 showing the build errors

Вот код, с которым возникают проблемы в 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);
        }
    }
}

Ответы

Ответ 1

замените строку

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

с

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);

Надеюсь, что это поможет,

Ответ 2

Вот как вы можете отправить электронное письмо через Microsoft Office Outlook. В моем случае я использовал Office 2010, но я полагаю, что он должен работать с более новыми версиями.

В приведенном выше примере выше отображается сообщение. Он не отправляет его. Кроме того, он не компилируется.

Итак, сначала вам нужно добавить эти ссылки в проект .NET:

введите описание изображения здесь

Как я сказал в своем комментарии к своему OP:

Вам нужно будет добавить следующие ссылки: (1) На вкладке .NET добавьте Microsoft.Office.Tools.Outlook для runtime v.4.0. *, Затем (2) снова с вкладки .NET добавьте Microsoft.Office.Interop.Outlook для версии 14.0.0.0 в моем случае и (3) Объект COM Объектная библиотека Microsoft Office 12.0 для Microsoft.Office.Core.

Затем здесь код для отправки сообщений электронной почты:

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;
    }

И вот как вы его используете:

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);

Ответ 3

Вам нужно бросить app.CreateItem(Outlook.OlItemType.olMailItem)
объект в
Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem)
для изображения Outlook.MailItem тип
 так как не доступно неявное литье.

Заменить

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

с

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