C# 通过C通过Outlook 2010发送电子邮件#
我正在尝试从我的C#控制台应用程序中发送电子邮件。我已经添加了引用和使用语句,但似乎还没有添加我需要的所有内容。这是我第一次尝试这样做,所以我想有些事情我已经忘记了 我从MSDN网站上得到了这个代码片段 这是我在VS2010中遇到问题的代码C# 通过C通过Outlook 2010发送电子邮件#,c#,email,reference,outlook,office-2010,C#,Email,Reference,Outlook,Office 2010,我正在尝试从我的C#控制台应用程序中发送电子邮件。我已经添加了引用和使用语句,但似乎还没有添加我需要的所有内容。这是我第一次尝试这样做,所以我想有些事情我已经忘记了 我从MSDN网站上得到了这个代码片段 这是我在VS2010中遇到问题的代码 using System; using System.Configuration; using System.IO; using System.Net; using System.Net.Mail; using System.Runtime.Interop
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);
}
}
}
更换线路
Outlook.MailItem mailItem = (Outlook.MailItem)
this.Application.CreateItem(Outlook.OlItemType.olMailItem);
与
希望这有帮助,这是您通过Microsoft Office Outlook发送电子邮件的方式。在我的例子中,我使用的是Office2010,但我认为它应该适用于较新的版本 上面的向上投票的示例仅显示消息。它不会把它发送出去。而且它不编译 因此,首先需要将这些引用添加到
.NET
项目中:
就像我在评论他的作品时说的:
您需要添加以下引用:(1)从.NET选项卡添加
Microsoft.Office.Tools.Outlook for runtime v.4.0.*,然后再次执行(2)
从.NET选项卡添加Microsoft.Office.Interop.Outlook版本
14.0.0.0,以及(3)用于Microsoft.Office.Core的COM对象Microsoft Office 12.0对象库
下面是发送电子邮件的代码:
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: "me@somewhere.com") -- 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: "recipient@gmail.com", or "recipient1@gmail.com; recipient2@gmail.com")
//'sCc' = email address sending to as Carbon Copy option. Can be multiple. In that case separate with semicolons or commas. (ex: "recipient@gmail.com", or "recipient1@gmail.com; recipient2@gmail.com")
//'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;
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
Net系统;
使用系统配置;
使用System.IO;
使用System.Net.Mail;
使用System.Runtime.InteropServices;
使用Outlook=Microsoft.Office.Interop.Outlook;
使用Office=Microsoft.Office.Core;
公共枚举主体类型
{
纯文本,
RTF,
HTML
}
//....
public static bool sendmailviaolook(字符串sFromAddress、字符串sToAddress、字符串sCc、字符串ssobject、字符串sBody、BodyType BodyType、列表arrAttachments=null、字符串sBcc=null)
{
//通过Office Outlook 2010发送电子邮件
//“sFromAddress”=从发送的电子邮件地址(例如:me@somewhere.com“”--此帐户必须存在于Outlook中。只允许使用一个电子邮件地址!
//“sToAddress”=发送到的电子邮件地址。可以是多个。在这种情况下,请用分号或逗号分隔。(例如:recipient@gmail.com“,或”recipient1@gmail.com; recipient2@gmail.com")
//“sCc”=作为副本选项发送到的电子邮件地址。可以是多个。在这种情况下,用分号或逗号分隔。(例如:recipient@gmail.com“,或”recipient1@gmail.com; recipient2@gmail.com")
//“SSObject”=纯文本形式的电子邮件主题
//“sBody”=电子邮件正文。数据类型取决于“bodyType”
//“bodyType”=“sBody”中的文本类型:纯文本、HTML或RTF
//“ArraAttachments”=如果不为空,则必须是要附加到电子邮件的绝对文件路径列表
//“sBcc”=单个电子邮件地址用作盲拷贝,或null不使用
//返回:
//=如果成功,则为true
布尔-布雷斯=假;
尝试
{
//获取Outlook COM对象
Outlook.Application app=新建Outlook.Application();
Outlook.MailItem newMail=(Outlook.MailItem)app.CreateItem(Outlook.OlItemType.olMailItem);
//解析“sToAddress”
如果(!string.IsNullOrWhiteSpace(sToAddress))
{
字符串[]arrAddTos=sToAddress.Split(新字符[]{';',','});
foreach(arrAddTos中的字符串strAddr)
{
if(!string.IsNullOrWhiteSpace(strAddr)&&
strAddr.IndexOf('@')!=-1)
{
Add(strAddr.Trim());
}
其他的
抛出新异常(“地址错误:+sToAddress”);
}
}
其他的
抛出新异常(“必须指定地址”);
//解析“sCc”
如果(!string.IsNullOrWhiteSpace(sCc))
{
字符串[]arrAddTos=sCc.Split(新字符[]{';',','});
foreach(arrAddTos中的字符串strAddr)
{
if(!string.IsNullOrWhiteSpace(strAddr)&&
strAddr.IndexOf('@')!=-1)
{
Add(strAddr.Trim());
}
其他的
抛出新异常(“坏CC地址:+sCc”);
}
}
//密件抄送是空的吗?
如果(!string.IsNullOrWhiteSpace(sBcc))
{
newMail.BCC=sBcc.Trim();
}
//解决所有问题
如果(!newMail.Recipients.ResolveAll())
{
抛出新异常(“未能解析所有收件人:“+sToAddress+”;“+sCc”);
}
//设置消息的类型
开关(车身型)
{
case BodyType.HTML:
newMail.HTMLBody=sbbody;
打破
case BodyType.RTF:
newMail.RTFBody=sbbody;
打破
case BodyType.PlainText:
newMail.Body=sBody;
打破
违约:
抛出新异常(“错误的电子邮件正文类型:“+bodyType”);
}
if(数组附件!=null)
{
//添加附件
foreach(数组中的字符串strPath)
{
if(File.Exists(strPath))
{
newMail.Attachments.Add(strPath);
}
其他的
抛出新异常(“未找到附件文件:\”“+strPath+\”);
}
}
//添加主题
如果(!string.IsNullOrWhiteSpace(SSObject))
newMail.Subject=ssObject;
Outlook.Accounts=app.Session.Accounts;
Outlook.Account acc=null;
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: "me@somewhere.com") -- 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: "recipient@gmail.com", or "recipient1@gmail.com; recipient2@gmail.com")
//'sCc' = email address sending to as Carbon Copy option. Can be multiple. In that case separate with semicolons or commas. (ex: "recipient@gmail.com", or "recipient1@gmail.com; recipient2@gmail.com")
//'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("senders_email@somewhere.com",
"john.doe@hotmail.com, jane_smith@gmail.com", null,
"Test email from script - " + DateTime.Now.ToString(),
"My message body - " + DateTime.Now.ToString(),
BodyType.PlainText,
arrAttachFiles,
null);
Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.MailItem mailItem = (Outlook.MailItem)app.CreateItem(Outlook.OlItemType.olMailItem);