Sending email using C #

I need to send an email through my C # application.

I came from VB 6 background and had a lot of bad experience with MAPI control. First of all, MAPI did not support HTML emails, and secondly, all emails were sent to my default mailbox. So I still had to click Submit.

If I need to send massive html files (100-200), what would be the best way to do this in C #?

Thanks in advance.

+46
c # email
Jan 16 '09 at 8:52
source share
10 answers

You can use the System.Net.Mail.MailMessage class of the .NET platform.

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("test@example.com", "TestFromName"); MailAddress to = new MailAddress("test2@example.com", "TestToName"); MailMessage myMail = new System.Net.Mail.MailMessage(from, to); // add ReplyTo MailAddress replyto = new MailAddress("reply@example.com"); 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; } 
+73
Jan 16 '09 at 8:56
source share

The best way to send bulk emails for a faster way is to use threads.I wrote this console application to send bulk emails. I split the primary email id into two batches by creating two thread pools.

 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 defined 10 recipients in the array list for the sample. It will create two batches of letters to create two thread pools for sending letters. You can also get data from your database.

You can use this code by copying and pasting it into a console application. (Replacing the program.cs file). Then the application will be ready to use.

Hope this helps you :).

+16
Nov 06 '09 at 12:08
source share

The code:

 using System.Net.Mail new SmtpClient("smtp.server.com", 25).send("from@email.com", "to@email.com", "subject", "body"); 

Bulk letters:

SMTP servers usually have a limit on the number of connections that they can handle right away, if you try to send hundreds of emails, the application may seem unresponsive.

Solutions:

  • If you are creating WinForm, use BackgroundWorker to process the queue.
  • If you are using an IIS SMTP server or an SMTP server with an outbox folder, you can use SmtpClient (). PickupDirectoryLocation = "c: / smtp / outboxFolder"; This will allow your system to respond.
  • If you are not using a local SMTP server, you can create a system service to use Filewatcher to control the breadwinner than to process any emails that you get there.
+9
Mar 03 '09 at 16:46
source share

The .NET framework has built-in classes that let you send emails through your application.

You should look into the System.Net.Mail namespace, where you will find the MailMessage and SmtpClient classes. You can set the BodyFormat of the MailMessage class in MailFormat.Html.

It can also be useful if you use the AlternateViews property of the MailMessage class so that you can provide a text version of your mail so that it can be read by clients that do not support HTML.

http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx

+4
Jan 16 '09 at 8:56
source share

You can send email using SMTP or CDO

using SMTP:

 mail.From = new MailAddress("your_email_address@gmail.com"); 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.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 Address

Source: C # CDO Email

+3
Jan 20 '14 at 7:25
source share

I can highly recommend the aspNetEmail library: http://www.aspnetemail.com/

System.Net.Mail will take you somewhere if your needs are only basic, but if you encounter difficulties, contact aspNetEmail. It saved me a ton of time, and I know other developers who swear by them too!

+2
Mar 10 '09 at 12:43
source share

Use the System.Net.Mail namespace. Here is the link to the MSDN page

You can send emails using the SmtpClient class.

I rephrased the sample code, so check the MSDN for details.

 MailMessage message = new MailMessage( "fromemail@contoso.com", "toemail@contoso.com", "Subject goes here", "Body goes here"); SmtpClient client = new SmtpClient(server); client.Send(message); 

The best way to send a lot of letters would be to put something like this in forloop and send!

+1
Jan 16 '09 at 9:00
source share

Take a look at the FluentEmail library. I wrote about it here

You have a nice and fast api for your needs:

 Email.FromDefault() .To("you@domain.com") .Subject("New order has arrived!") .Body("The order details are…") .Send(); 
0
Feb 23 '14 at 20:32
source share

Let's make something as a complete solution :). Maybe this can help. This solution is for sending one email content and one file attachment (or without attachments) to multiple email addresses. Of course, sending only one email is also possible. The result is a List object with data about what is in order and what is not.

 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; } } } 
0
Jul 19 '18 at 12:15
source share

You can use Mailkit . MailKit is a cross-platform .NET library for open source email clients, based on MimeKit and optimized for mobile devices.

It has more features and improvements than System.Net.Mail

  • Completely revocable Pop3Client with support for STLS, UIDL, APOP, PIPELINING, UTF8 and LANG. Client-side sorting and creation of message flows (Ordinal subject and Jamie Zawinski flow algorithms are supported).
  • Asynchronous versions of all methods that fall into the network.
  • Signature support S / MIME, OpenPGP and DKIM through MimeKit.
  • Microsoft TNEF support through MimeKit.

See this example you can send mail

  MimeMessage mailMessage = new MimeMessage(); mailMessage.From.Add(new MailboxAddress(senderName, sender@address.com)); mailMessage.Sender = new MailboxAddress(senderName, sender@address.com); 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("user@name.com", "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 .

0
Aug 04 '18 at 10:59
source share



All Articles