C# Send bulk email - c#

I am wondering what the best way to send bulk emails is using System.Net.Mail and C#.
Is it a good idea to send emails in batches?
Should I use the to field or BCC?

I prefer using the To field and send e-mails one at a time in stead of using the BCC field. This way the receiver sees his e-mail address in the TO field (less spam-sensitive) and you can personalize the e-mails per user in the future.
For the sending, you should use batches to prevent timeouts and heavy server loads. You could use a queue for all the e-mails and send them using a configurable schedule using a service, scheduled task, or whatever.

If you do send a single email to multiple recipient and if it's for sending emails to people who don't know each other you should definitely use the BCC field otherwise you're sure to make a lot of people quite angry when you're giving away their email addresses to strangers (and you might also be breaking some kind of data protection law depending on where you live).

bulk Emails using mailkit you have to import it by nuget manager
set in gmail https://myaccount.google.com/lesssecureapps?pli=1 to be on
public void ReadFileAndSend()
{
using (StreamReader reader = new StreamReader(#"d:\Email.txt"))
{
while (!(reader.ReadLine() == null))
{
String line = reader.ReadLine();
if (line != "")
{
try
{
Send("", line.Trim());
Thread.Sleep(500);
}
catch
{
}
}
}
Console.ReadLine();
}
}
public void Send(String FromAddress,String ToAddress)
{
try
{
string FromAdressTitle = "";
string ToAdressTitle = "";
string Subject = "";
string BodyContent = "";
string SmtpServer = "smtp.gmail.com";
int SmtpPortNumber = 587;
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
mimeMessage.Subject = Subject;
mimeMessage.Body = new TextPart("html")
{
Text = BodyContent
};
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect(SmtpServer, SmtpPortNumber, false);
client.Authenticate("your email", "pass");
client.Send(mimeMessage);
Console.WriteLine("The mail has been sent successfully !!");
client.Disconnect(true);
}
}
catch (Exception ex)
{
throw ex;
}
}

Related

How do I send an email internally from a noreply#example.com to another person using smtp

I am creating an app that sends a PDF of how many hours I have worked out during the week. I am using Visual Studio 2017 using C#. I have it set up so that the program sends you the hours worked out from a random email that I made up.
I want it to send internally so the router will allow for internal made up addresses like noreply#example.com so that someone could receive the pdf but it wouldn't be a real email. I have just been using a made up email and that is not how I want it to be done.
Take a look at the SmtpClient Class.
A C# example of using said class can be found at the link but I'm copying it here for posterity. You'll note the "from" address is literally just a String - it needn't be valid.
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace Examples.SmptExamples.Async
{
public class SimpleAsynchronousExample
{
static bool mailSent = false;
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string) e.UserState;
if (e.Cancelled)
{
Console.WriteLine("[{0}] Send canceled.", token);
}
if (e.Error != null)
{
Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
} else
{
Console.WriteLine("Message sent.");
}
mailSent = true;
}
public static void Main(string[] args)
{
// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient(args[0]);
// Specify the e-mail sender.
// Create a mailing address that includes a UTF8 character
// in the display name.
MailAddress from = new MailAddress("jane#contoso.com",
"Jane " + (char)0xD8+ " Clayton",
System.Text.Encoding.UTF8);
// Set destinations for the e-mail message.
MailAddress to = new MailAddress("ben#contoso.com");
// Specify the message content.
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test e-mail message sent by an application. ";
// Include some non-ASCII characters in body and subject.
string someArrows = new string(new char[] {'\u2190', '\u2191', '\u2192', '\u2193'});
message.Body += Environment.NewLine + someArrows;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "test message 1" + someArrows;
message.SubjectEncoding = System.Text.Encoding.UTF8;
// Set the method that is called back when the send operation ends.
client.SendCompleted += new
SendCompletedEventHandler(SendCompletedCallback);
// The userState can be any object that allows your callback
// method to identify this send operation.
// For this example, the userToken is a string constant.
string userState = "test message1";
client.SendAsync(message, userState);
Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
string answer = Console.ReadLine();
// If the user canceled the send, and mail hasn't been sent yet,
// then cancel the pending operation.
if (answer.StartsWith("c") && mailSent == false)
{
client.SendAsyncCancel();
}
// Clean up.
message.Dispose();
Console.WriteLine("Goodbye.");
}
}
}

Email sending with attachment issue

I am trying to send an email message to different users (with an attachment). The email is being sent, but only one user receives the attachment (image file). Other recipients receive something like empty picture, or picture with name and zero bytes.
I don't really understand what is going wrong. Here is code that I used for sending emails:
public void SendWithFile(string recipientName, string body, string subject = null, HttpPostedFileBase emailFile = null)
{
using (var msg = new MailMessage())
{
msg.To.Add(recipientName);
msg.From = new MailAddress(ConfigurationManager.AppSettings["MailServerSenderAdress"]);
msg.Subject = subject;
msg.Body = body;
msg.SubjectEncoding = Encoding.UTF8;
msg.BodyEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.Normal;
using (Attachment data = new Attachment(emailFile.InputStream, Path.GetFileName(emailFile.FileName), emailFile.ContentType))
{
msg.Attachments.Add(data);
using (var client = new SmtpClient())
{
//client configs
try
{
client.Send(msg);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
}
and here is where I call the send email method:
foreach (var recipent in notesRecipients)
{
if (!string.IsNullOrEmpty(userEmail))
{
if (emailFile != null)
emailService.SendWithFile(userEmail, message, null, emailFile);
}
}
You have to seek the stream from the beginning like below before you send the attachment:
emailFile.InputStream.Position = 0;
For more info you can refer to this question here: link

Sending email in C#

I am working on a page where I have to send an email in C#.
I followed the codes on
http://blogs.msdn.com/b/mariya/archive/2006/06/15/633007.aspx
and came upon this two exceptions
A first chance exception of type 'System.Net.Mail.SmtpException' occurred in System.dll. A first chance exception of type
'System.Threading.ThreadAbortException' occurred in mscorlib.dll
Here are the codes I implemented. I can't seem to figure what went wrong.
//Send email notification - removed actual email for this question
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
MailAddress from = new MailAddress("myemail#gmail.com", "My name is here");
MailAddress to = new MailAddress("anotherpersonsemail#gmail.com", "Subject here");
MailMessage message = new MailMessage(from, to);
message.Body = "Thank you";
message.Subject = "Successful submission";
NetworkCredential myCreds = new NetworkCredential("myemail#gmail.com",
"mypassword", "");
client.Credentials = myCreds;
try
{
client.Send(message);
Console.Write(ex.Message.ToString());
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
}
For sharing purposes, I managed to resolve my problem by enabling access for less secure apps in Gmail.
It works like a charm now! https://www.google.com/settings/security/lesssecureapps
To authenticate SMTP in Outlook, the articles below are very useful too.
http://www.tradebooster.com/web-hosting-articles/how-to-enable-smtp-authentication-in-outlook-2010/
https://www.authsmtp.com/outlook-2010/default-port.html
//bulk Emails using mailkit you have to import it by nuget manager
//set in gmail https://myaccount.google.com/lesssecureapps?pli=1 to be on
// Read Text File
public void ReadFileAndSend()
{
using (StreamReader reader = new StreamReader(#"d:\Email.txt"))
{
while (!(reader.ReadLine() == null))
{
String line = reader.ReadLine();
if (line != "")
{
try
{
Send("", line.Trim());
Thread.Sleep(500);
}
catch
{
}
}
}
Console.ReadLine();
}
}
public void Send(String FromAddress,String ToAddress)
{
try
{
string FromAdressTitle = "";
string ToAdressTitle = "";
string Subject = "";
string BodyContent = "";
string SmtpServer = "smtp.gmail.com";
int SmtpPortNumber = 587;
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
mimeMessage.Subject = Subject;
mimeMessage.Body = new TextPart("html")
{
Text = BodyContent
};
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect(SmtpServer, SmtpPortNumber, false);
client.Authenticate("your email", "pass");
client.Send(mimeMessage);
Console.WriteLine("The mail has been sent successfully !!");
client.Disconnect(true);
}
}
catch (Exception ex)
{
throw ex;
}
}
Answer Update 2023
After Google introduced a Two-step verification system in Google Accounts, it's not easy to use Gmail for your own personal usage so to solve this problem, I figured out a way to use Gmail as an email medium to send emails using C#.
The C# code for email service is included here: https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html
Following just the 2-step tutorial from the above link, you can fix your issue in no time.

Send SMTP mail when an exception occurs

I'd be grateful if someone could tell me if I'm on the right track... Basically, I have a webservice i need to run for my app, I've put it into a try catch, if the try fails I want the catch to send me an email message with the details of the exception.
try
{
// run webservice here
}
catch (Exception ex)
{
string strTo = "scott#...";
string strFrom = "web#...";
string strSubject = "Webservice Not Run";
SmtpMail.SmtpServer = "thepostoffice";
SmtpMail.Send(strFrom, strTo, strSubject, ex.ToString());
}
Yes you are but you'd better wrapp yor exception handler in some kind of logger or use existing ones like Log4Net or NLog.
A quick and easy way to send emails whenever an Exception occurs can be done like this:
SmtpClient Server = new SmtpClient();
Server.Host = ""; //example: smtp.gmail.com
Server.Port = ; //example: 587 if you're using gmail
Server.EnableSsl = true; //If the smtp server requires it
//Server Credentials
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = "youremail#gmail.com";
credentials.Password = "your password here";
//assign the credential details to server
Server.Credentials = credentials;
//create sender's address
MailAddress sender = new MailAddress("Sender email address", "sender name");
//create receiver's address
MailAddress receiver = new MailAddress("receiver email address", "receiver name");
MailMessage message = new MailMessage(sender, receiver);
message.Subject = "Your Subject";
message.Body = ex.ToString();
//send the email
Server.Send(message);
Yes this the right way, if you don't want to use any logger tool.You can create function SendMail(string Exceptioin) to one of the your common class and than call this function from each catch block

opennetcf.net.mail attachment help

Thanks for looking at my question.
I am trying to figure out attachments for OpenNetCF.Net.Mail. Here is the code for my SendMail function:
public static void SendMessage(string subject,
string messageBody,
string fromAddress,
string toAddress,
string ccAddress)
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
MailAddress address = new MailAddress(fromAddress);
// Set the sender's address
message.From = address;
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
// Allow multiple "Cc" addresses to be separated by a semi-colon
if (ccAddress.Trim().Length > 0)
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
// Set the subject and message body text
message.Subject = subject;
message.Body = messageBody;
// TODO: *** Modify for your SMTP server ***
// Set the SMTP server to be used to send the message
client.Host = "smtp.dscarwash.com";
string domain = "dscarwash.com";
client.Credentials = new SmtpCredential("mailuser", "dscarwash10", domain);
// Send the e-mail message
try
{
client.Send(message);
}
catch (Exception e)
{
string data = e.ToString();
}
}
It is supposed to be a matter of tweaking it in the following way to allow attachments:
Attachment myAttachment = new Attachment();
message.Attachments.Add(myAttachment);
The problem is that I cannot figure out how to get the attachment to add. The lines above should be it with something else in the middle where I actually tell it what file I would like to attach. Any help on this matter will be greatly appreciated.
Thanks again!
As per this MSDN documentation, you can specify the filename of the attachment as a parameter. Thus, you can give the fullpath as the string parameter.
They have AttachmentBase which can be used to construct a email attachment. However, we cannot add the instance of AttachmentBase to the attachments of email message.
I think the Attachment class should inherit from AttachmentBase. I think this maybe a defect.

Categories

Resources