使用 C# 发送电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/449887/
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
Sending E-mail using C#
提问by MegaByte
I need to send email via my C# app.
我需要通过我的 C# 应用程序发送电子邮件。
I come from a VB 6 background and had a lot of bad experiences with the MAPI control. First of all, MAPI did not support HTML emails and second, all the emails were sent to my default mail outbox. So I still needed to click on send receive.
我来自 VB 6 背景,在 MAPI 控件方面有很多糟糕的经历。首先,MAPI 不支持 HTML 电子邮件,其次,所有电子邮件都发送到我的默认邮件发件箱。所以我仍然需要点击发送接收。
If I needed to send bulk html bodied emails (100 - 200), what would be the best way to do this in C#?
如果我需要发送批量 html 正文电子邮件(100 - 200),在 C# 中执行此操作的最佳方法是什么?
Thanks in advance.
提前致谢。
采纳答案by splattne
You could use the System.Net.Mail.MailMessageclass of the .NET framework.
您可以使用.NET 框架的System.Net.Mail.MailMessage类。
You can find the MSDN documentation here.
Here is a simple example (code snippet):
这是一个简单的例子(代码片段):
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
...
try
{
SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net");
// set smtp-client with basicAuthentication
mySmtpClient.UseDefaultCredentials = false;
System.Net.NetworkCredential basicAuthenticationInfo = new
System.Net.NetworkCredential("username", "password");
mySmtpClient.Credentials = basicAuthenticationInfo;
// add from,to mailaddresses
MailAddress from = new MailAddress("[email protected]", "TestFromName");
MailAddress to = new MailAddress("[email protected]", "TestToName");
MailMessage myMail = new System.Net.Mail.MailMessage(from, to);
// add ReplyTo
MailAddress replyTo = new MailAddress("[email protected]");
myMail.ReplyToList.Add(replyTo);
// set subject and encoding
myMail.Subject = "Test message";
myMail.SubjectEncoding = System.Text.Encoding.UTF8;
// set body-message and encoding
myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
myMail.BodyEncoding = System.Text.Encoding.UTF8;
// text or html
myMail.IsBodyHtml = true;
mySmtpClient.Send(myMail);
}
catch (SmtpException ex)
{
throw new ApplicationException
("SmtpException has occured: " + ex.Message);
}
catch (Exception ex)
{
throw ex;
}
回答by Frederik Gheysels
The .NET framework has some built-in classes which allows you to send e-mail via your app.
.NET 框架有一些内置类,允许您通过应用程序发送电子邮件。
You should take a look in the System.Net.Mail namespace, where you'll find the MailMessage and SmtpClient classes. You can set the BodyFormat of the MailMessage class to MailFormat.Html.
您应该查看 System.Net.Mail 命名空间,您将在其中找到 MailMessage 和 SmtpClient 类。您可以将 MailMessage 类的 BodyFormat 设置为 MailFormat.Html。
It could also be helpfull if you make use of the AlternateViews property of the MailMessage class, so that you can provide a plain-text version of your mail, so that it can be read by clients that do not support HTML.
如果您使用 MailMessage 类的 AlternateViews 属性,它也可能会有所帮助,以便您可以提供邮件的纯文本版本,以便不支持 HTML 的客户端可以读取它。
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx
回答by bentford
Use the namespace System.Net.Mail. Here is a link to the MSDN page
使用命名空间 System.Net.Mail。 这是 MSDN 页面的链接
You can send emails using SmtpClient class.
您可以使用 SmtpClient 类发送电子邮件。
I paraphrased the code sample, so checkout MSDNfor details.
我解释了代码示例,因此请查看 MSDN 了解详细信息。
MailMessage message = new MailMessage(
"[email protected]",
"[email protected]",
"Subject goes here",
"Body goes here");
SmtpClient client = new SmtpClient(server);
client.Send(message);
The best way to send many emails would be to put something like this in forloop and send away!
发送大量电子邮件的最佳方式是将这样的内容放入 forloop 并发送出去!
回答by missaghi
Code:
代码:
using System.Net.Mail
new SmtpClient("smtp.server.com", 25).send("[email protected]",
"[email protected]",
"subject",
"body");
Mass Emails:
群发邮件:
SMTP servers usually have a limit on the number of connection hat can handle at once, if you try to send hundreds of emails you application may appear unresponsive.
SMTP 服务器通常对一次可以处理的连接数量有限制,如果您尝试发送数百封电子邮件,您的应用程序可能会无响应。
Solutions:
解决方案:
- If you are building a WinForm then use a BackgroundWorker to process the queue.
- If you are using IIS SMTP server or a SMTP server that has an outbox folder then you can use SmtpClient().PickupDirectoryLocation = "c:/smtp/outboxFolder"; This will keep your system responsive.
- If you are not using a local SMTP server than you could build a system service to use Filewatcher to monitor a forlder than will then process any emails you drop in there.
- 如果您正在构建 WinForm,则使用 BackgroundWorker 来处理队列。
- 如果您使用的是 IIS SMTP 服务器或具有发件箱文件夹的 SMTP 服务器,那么您可以使用 SmtpClient().PickupDirectoryLocation = "c:/smtp/outboxFolder"; 这将使您的系统保持响应。
- 如果您没有使用本地 SMTP 服务器,那么您可以构建一个系统服务来使用 Filewatcher 来监控一个文件夹,然后处理您发送到那里的任何电子邮件。
回答by JMS
I can strongly recommend the aspNetEmail library: http://www.aspnetemail.com/
我强烈推荐 aspNetEmail 库:http: //www.aspnetemail.com/
The System.Net.Mail
will get you somewhere if your needs are only basic, but if you run into trouble, please check out aspNetEmail. It has saved me a bunch of time, and I know of other develoeprs who also swear by it!
System.Net.Mail
如果您的需求只是基本的,它会带您到某个地方,但如果您遇到麻烦,请查看 aspNetEmail。它为我节省了大量时间,而且我知道其他开发人员也对它发誓!
回答by Vijaya Priya
The best way to send bulk emails for more faster way is to use threads.I have written this console application for sending bulk emails.I have seperated the bulk email ID into two batches by creating two thread pools.
以更快的方式发送批量电子邮件的最佳方式是使用线程。我编写了这个用于发送批量电子邮件的控制台应用程序。我通过创建两个线程池将批量电子邮件 ID 分为两批。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Mail;
namespace ConsoleApplication1
{
public class SendMail
{
string[] NameArray = new string[10] { "Recipient 1",
"Recipient 2",
"Recipient 3",
"Recipient 4",
"Recipient 5",
"Recipient 6",
"Recipient 7",
"Recipient 8",
"Recipient 9",
"Recipient 10"
};
public SendMail(int i, ManualResetEvent doneEvent)
{
Console.WriteLine("Started sending mail process for {0} - ", NameArray[i].ToString() + " at " + System.DateTime.Now.ToString());
Console.WriteLine("");
SmtpClient mailClient = new SmtpClient();
mailClient.Host = Your host name;
mailClient.UseDefaultCredentials = true;
mailClient.Port = Your mail server port number; // try with default port no.25
MailMessage mailMessage = new MailMessage(FromAddress,ToAddress);//replace the address value
mailMessage.Subject = "Testing Bulk mail application";
mailMessage.Body = NameArray[i].ToString();
mailMessage.IsBodyHtml = true;
mailClient.Send(mailMessage);
Console.WriteLine("Mail Sent succesfully for {0} - ",NameArray[i].ToString() + " at " + System.DateTime.Now.ToString());
Console.WriteLine("");
_doneEvent = doneEvent;
}
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("Thread process completed for {0} ...",threadIndex.ToString() + "at" + System.DateTime.Now.ToString());
_doneEvent.Set();
}
private ManualResetEvent _doneEvent;
}
public class Program
{
static int TotalMailCount, Mailcount, AddCount, Counter, i, AssignI;
static void Main(string[] args)
{
TotalMailCount = 10;
Mailcount = TotalMailCount / 2;
AddCount = Mailcount;
InitiateThreads();
Thread.Sleep(100000);
}
static void InitiateThreads()
{
//One event is used for sending mails for each person email id as batch
ManualResetEvent[] doneEvents = new ManualResetEvent[Mailcount];
// Configure and launch threads using ThreadPool:
Console.WriteLine("Launching thread Pool tasks...");
for (i = AssignI; i < Mailcount; i++)
{
doneEvents[i] = new ManualResetEvent(false);
SendMail SRM_mail = new SendMail(i, doneEvents[i]);
ThreadPool.QueueUserWorkItem(SRM_mail.ThreadPoolCallback, i);
}
Thread.Sleep(10000);
// Wait for all threads in pool to calculation...
//try
//{
// // WaitHandle.WaitAll(doneEvents);
//}
//catch(Exception e)
//{
// Console.WriteLine(e.ToString());
//}
Console.WriteLine("All mails are sent in this thread pool.");
Counter = Counter+1;
Console.WriteLine("Please wait while we check for the next thread pool queue");
Thread.Sleep(5000);
CheckBatchMailProcess();
}
static void CheckBatchMailProcess()
{
if (Counter < 2)
{
Mailcount = Mailcount + AddCount;
AssignI = Mailcount - AddCount;
Console.WriteLine("Starting the Next thread Pool");
Thread.Sleep(5000);
InitiateThreads();
}
else
{
Console.WriteLine("No thread pools to start - exiting the batch mail application");
Thread.Sleep(1000);
Environment.Exit(0);
}
}
}
}
I have defined 10 recepients in the array list for a sample.It will create two batches of emails to create two thread pools to send mails.You can pick the details from your database also.
我在一个示例的数组列表中定义了 10 个收件人。它将创建两批电子邮件以创建两个线程池来发送邮件。您也可以从数据库中选择详细信息。
You can use this code by copying and pasting it in a console application.(Replacing the program.cs file).Then the application is ready to use.
您可以通过将其复制并粘贴到控制台应用程序中来使用此代码。(替换 program.cs 文件)。然后应用程序就可以使用了。
I hope this helps you :).
我希望这可以帮助你 :)。
回答by Jerrym
You can send email using SMTP or CDO
您可以使用 SMTP 或 CDO 发送电子邮件
using SMTP:
使用 SMTP:
mail.From = new MailAddress("[email protected]");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
using CDO
使用 CDO
CDO.Message oMsg = new CDO.Message();
CDO.IConfiguration iConfg;
iConfg = oMsg.Configuration;
ADODB.Fields oFields;
oFields = iConfg.Fields;
ADODB.Field oField = oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"];
oFields.Update();
oMsg.Subject = "Test CDO";
oMsg.From = "from_address";
oMsg.To = "to_address";
oMsg.TextBody = "CDO Mail test";
oMsg.Send();
Source : C# SMTP Email
来源:C# SMTP 电子邮件
Source: C# CDO Email
来源:C# CDO 电子邮件
回答by Dennis Nerush
Take a look at the FluentEmail library. I've blogged about it here
查看 FluentEmail 库。我已经在这里写了关于它的博客
You have a nice and fluent api for your needs:
你有一个漂亮流畅的 api 来满足你的需求:
Email.FromDefault()
.To("[email protected]")
.Subject("New order has arrived!")
.Body("The order details are…")
.Send();
回答by user2721448
Let's make something as a full solution :). Maybe it can help as well. It is a solution for sending one email content and one attach file (or without attach) to many Email addresses. Of course sending just one email is possibility as well. Result is List object with data what is OK and what is not.
让我们把一些东西作为一个完整的解决方案:)。也许它也可以提供帮助。它是一种将一个电子邮件内容和一个附件(或不带附件)发送到多个电子邮件地址的解决方案。当然,也可以只发送一封电子邮件。结果是包含数据的 List 对象,哪些是可以的,哪些不是。
namespace SmtpSendingEmialMessage
{
public class EmailSetupData
{
public string EmailFrom { get; set; }
public string EmailUserName { get; set; }
public string EmailPassword { get; set; }
public string EmailSmtpServerName { get; set; }
public int EmailSmtpPortNumber { get; set; }
public Boolean SSLActive { get; set; } = false;
}
public class SendingResultData
{
public string SendingEmailAddress { get; set; }
public string SendingEmailSubject { get; set; }
public DateTime SendingDateTime { get; set; }
public Boolean SendingEmailSuccess { get; set; }
public string SendingEmailMessage { get; set; }
}
public class OneRecData
{
public string RecEmailAddress { get; set; } = "";
public string RecEmailSubject { get; set; } = "";
}
public class SendingProcess
{
public string EmailCommonSubjectOptional { get; set; } = "";
private EmailSetupData EmailSetupParam { get; set; }
private List<OneRecData> RecDataList { get; set; }
private string EmailBodyContent { get; set; }
private Boolean IsEmailBodyHtml { get; set; }
private string EmailAttachFilePath { get; set; }
public SendingProcess(List<OneRecData> MyRecDataList, String MyEmailTextContent, String MyEmailAttachFilePath, EmailSetupData MyEmailSetupParam, Boolean EmailBodyHtml)
{
RecDataList = MyRecDataList;
EmailBodyContent = MyEmailTextContent;
EmailAttachFilePath = MyEmailAttachFilePath;
EmailSetupParam = MyEmailSetupParam;
IsEmailBodyHtml = EmailBodyHtml;
}
public List<SendingResultData> SendAll()
{
List<SendingResultData> MyResList = new List<SendingResultData>();
foreach (var js in RecDataList)
{
using (System.Net.Mail.MailMessage MyMes = new System.Net.Mail.MailMessage())
{
DateTime SadaJe = DateTime.Now;
Boolean IsOK = true;
String MySendingResultMessage = "Sending OK";
String MessageSubject = EmailCommonSubjectOptional;
if (MessageSubject == "")
{
MessageSubject = js.RecEmailSubject;
}
try
{
System.Net.Mail.MailAddress MySenderAdd = new System.Net.Mail.MailAddress(js.RecEmailAddress);
MyMes.To.Add(MySenderAdd);
MyMes.Subject = MessageSubject;
MyMes.Body = EmailBodyContent;
MyMes.Sender = new System.Net.Mail.MailAddress(EmailSetupParam.EmailFrom);
MyMes.ReplyToList.Add(MySenderAdd);
MyMes.IsBodyHtml = IsEmailBodyHtml;
}
catch(Exception ex)
{
IsOK = false;
MySendingResultMessage ="Sender or receiver Email address error." + ex.Message;
}
if (IsOK == true)
{
try
{
if (EmailAttachFilePath != null)
{
if (EmailAttachFilePath.Length > 5)
{
MyMes.Attachments.Add(new System.Net.Mail.Attachment(EmailAttachFilePath));
}
}
}
catch (Exception ex)
{
IsOK = false;
MySendingResultMessage ="Emial attach error. " + ex.Message;
}
if (IsOK == true)
{
using (System.Net.Mail.SmtpClient MyCl = new System.Net.Mail.SmtpClient())
{
MyCl.EnableSsl = EmailSetupParam.SSLActive;
MyCl.Host = EmailSetupParam.EmailSmtpServerName;
MyCl.Port = EmailSetupParam.EmailSmtpPortNumber;
try
{
MyCl.Credentials = new System.Net.NetworkCredential(EmailSetupParam.EmailUserName, EmailSetupParam.EmailPassword);
}
catch (Exception ex)
{
IsOK = false;
MySendingResultMessage = "Emial credential error. " + ex.Message;
}
if (IsOK == true)
{
try
{
MyCl.Send(MyMes);
}
catch (Exception ex)
{
IsOK = false;
MySendingResultMessage = "Emial sending error. " + ex.Message;
}
}
}
}
}
MyResList.Add(new SendingResultData
{
SendingDateTime = SadaJe,
SendingEmailAddress = js.RecEmailAddress,
SendingEmailMessage = MySendingResultMessage,
SendingEmailSubject = js.RecEmailSubject,
SendingEmailSuccess = IsOK
});
}
}
return MyResList;
}
}
}
回答by Naveen
You can use Mailkit. MailKit is an Open Source cross-platform .NET mail-client library that is based on MimeKit and optimized for mobile devices.
您可以使用Mailkit。MailKit 是一个开源的跨平台 .NET 邮件客户端库,它基于 MimeKit 并针对移动设备进行了优化。
It has more and advance features better than System.Net.Mail
它比System.Net.Mail具有更多和更先进的功能
- A fully-cancellable Pop3Client with support for STLS, UIDL, APOP, PIPELINING, UTF8, and LANG. Client-side sorting and threading of messages (the Ordinal Subject and the Jamie Zawinski threading algorithms are supported).
- Asynchronous versions of all methods that hit the network.
- S/MIME, OpenPGP and DKIM signature support via MimeKit.
- Microsoft TNEF support via MimeKit.
- 一个完全可取消的 Pop3Client,支持 STLS、UIDL、APOP、PIPELINING、UTF8 和 LANG。消息的客户端排序和线程处理(支持序数主题和 Jamie Zawinski 线程算法)。
- 访问网络的所有方法的异步版本。
- 通过 MimeKit 支持 S/MIME、OpenPGP 和 DKIM 签名。
- 通过 MimeKit 支持 Microsoft TNEF。
See this example you can send mail
看到这个例子你可以发送邮件
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(senderName, [email protected]));
mailMessage.Sender = new MailboxAddress(senderName, [email protected]);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.TextBody = "Hello There";
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("[email protected]", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
You can download from here.
你可以从这里下载。