This is my code to send lots of emails. I want to optimize this code to be sure that it will work and can successfully send all emails. What should I do? I know that putting interrupts between sending might be useful but how can I do this?
The main problem is avoiding classify emails as spam and decreasing number of failed sent emails.
var list = from c in context.Emails orderby c.EmailAddress select c.EmailAddress;
MailMessage mail = new MailMessage();
try
{
mail.From = new MailAddress(txtfrom.Text);
foreach (var c in list)
{
mail.To.Add(new MailAddress(c.ToString()));
}
mail.Subject = txtSub.Text;
mail.IsBodyHtml = true;
mail.Body = txtBody.Text;
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(
FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
}
catch (Exception)
{
//exception handling
}
I would advise you against adding all reciepients into the same mail message.
Rather use this code:
mail.From = new MailAddress(txtfrom.Text);
mail.Subject = txtSub.Text;
mail.IsBodyHtml = true;
mail.Body = txtBody.Text;
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
SmtpClient smtp = new SmtpClient();
foreach (var c in list)
{
mail.To.Clear();
mail.To.Add(new MailAddress(c.ToString()));
smtp.Send(mail);
}
With a little due diligence, this can be accomplished with a very simple console application which can be called from the Web form to dispatch the emails. By diligence, I mean to insert a pause between batches so that the mail server won't get bogged down. For example, if you were grabbing the addresses from a DB and sending them out, you could have something like:
if ((count >= 100) && (count % 100 == 0))
Thread.Sleep(30000);
-----------------------------------------
// Web form code-behind
// Pass subject and message strings as params to console app
ProcessStartInfo info = new ProcessStartInfo();
string arguments = String.Format(#"""{0}"" ""{1}""",
subjectText.Text.Replace(#"""", #""""""),
messageText.Text.Replace(#"""", #""""""));
info.FileName = MAILER_FILEPATH;
Process process = Process.Start(info.FileName, arguments);
Process.Start(info);
More info here: Calling Console Application from Web Form
Related
Anyone can help please.
I am using the following code for sending email from my ASP.Net, C# web forms application which generating the error. The same code is working for other application. My domain name contains a hyphen in it (-). Is that the reason? Do I need to see email configuration or server/domain level settings? Please help.
string smtpServer = "smtp.office365.com";
int port = 587;
using (MailMessage mail = new MailMessage())
{
using (SmtpClient SmtpServer = new SmtpClient(smtpServer))
{
mail.From = new MailAddress(_emailIDFrom);
mail.To.Add(_emailIDTo);
mail.Subject = _subject;
mail.IsBodyHtml = true;
mail.Body = _emailBody;
SmtpServer.Port = port;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential(_emailIDFrom, _emailIDFromPassword);
SmtpServer.EnableSsl = true;
try
{
SmtpServer.Send(mail);
return true;
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
return false;
}
}
}
My Tls code in Global.asax Application_Start as follows
if (ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Tls12) == false)
{
ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls12;
}
ERROR--
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 Client not authenticated to send mail. Error: 535 5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [DXXP273CA0023.AREP273.PROD.OUTLOOK.COM]
I am trying to send mail using GoDaddy mail server with SMTPClient in ASP.NET and my code is below , I have tried all the ports in GoDaddy but i couldn't send a mail
My code:
try
{
//Mail Message
MailMessage mM = new MailMessage();
//Mail Address
mM.From = new MailAddress("xxx#sender.com");
//receiver email id
mM.To.Add("xxx#receiver.com");
//subject of the email
mM.Subject = "your subject line will go here";
mM.Body = "Body of the email";
mM.IsBodyHtml = true;
//SMTP client
SmtpClient sC = new SmtpClient();
//credentials to login in to hotmail account
sC.Credentials = new NetworkCredential(username, password);
//port number for Hot mail
sC.Port = 25;
sC.Host = "smtpout.asia.secureserver.net";
sC.UseDefaultCredentials = false;
//enabled SSL
sC.EnableSsl = false;
sC.DeliveryMethod = SmtpDeliveryMethod.Network;
sC.Timeout = 40000;
//Send an email
sC.Send(mM);
}
catch (Exception ex)
{
var temp = ex.Message;
}
I have also used port no 465 with enablessl = true but no success
I was struggling with this too and found a solution.
The problem is that GoDaddy uses Implicit SSL (SMTPS) and this is NOT supported with System.Net.Mail.
It should be possible to use a GoDady Relay account, but then you can only send 250 emails per day AND the email sent will be SPAM unvisible at receiver side!
Then I found an open source library: http://sourceforge.net/projects/netimplicitssl/
You can get this package via NuGet in Visual Studio.
Search for: Aegis Implicit Mail.
I can tell you that this works perfectly !
private void _SendEmail()
{
try
{
var mail = "YourEmail#YourGoDaddyWebsite.com";
var host = "smtpout.europe.secureserver.net";
var user = "YourEmail#YourGoDaddyWebsite.com";
var pass = "YourGoDaddyPassword!";
//Generate Message
var message = new MimeMailMessage();
message.From = new MimeMailAddress(mail);
message.To.Add("receiver#website.com");
message.Subject = "Subject Text...";
message.Body = "Body Text...";
//Create Smtp Client
var mailer = new MimeMailer(host, 465);
mailer.User = user;
mailer.Password = pass;
mailer.SslType = SslMode.Ssl;
mailer.AuthenticationMode = AuthenticationType.Base64;
//Set a delegate function for call back
mailer.SendCompleted += compEvent;
mailer.SendMailAsync(message);
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
private void compEvent(object sender, AsyncCompletedEventArgs e)
{
if (e.UserState != null)
Console.Out.WriteLine(e.UserState.ToString());
Console.Out.WriteLine("is it canceled? " + e.Cancelled);
if (e.Error != null)
Console.Out.WriteLine("Error : " + e.Error.Message);
}
you should note you cannot sent non-html, or plain text emails. The message.IsBodyHtml member does not seem to work currently.
I am developing a website by using ASP.NET. In there I am sending emails to users.
Currently I am using this code to send email asynchronously to user. Emails are sending in background.
public static void SendEmail(string Path, string EmailTo)
{
Thread emailThread = new Thread(delegate()
{
try
{
string body = string.Empty;
using (StreamReader reader = new StreamReader(Path))
{
body = reader.ReadToEnd();
}
MailMessage mail = new MailMessage();
mail.From = new MailAddress("test#test.com");
mail.To.Add(EmailTo);
mail.Subject = "Test email";
mail.Body += body;
mail.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient("smtp.test.com");
smtpClient.Port = 587;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("test#test.com", "test");
smtpClient.EnableSsl = true;
smtpClient.SendCompleted += (s, e) =>
{
smtpClient.Dispose();
mail.Dispose();
};
try
{
smtpClient.Send(mail);
}
catch (Exception ex) { /* exception handling code here */ }
}
catch (Exception)
{
throw;
}
});
emailThread.IsBackground = true;
emailThread.Start();
}
So above code is working fine. But one day I got a problem. When I press the send button at the same time my internet connection was down. So email didn't get fired. Thats the time I realize that this email function need some mechanism to queue the emails and send it to users one by one according to the order in the queue. So if any email got undelivered or if network gets down then retry it. So how to achieve this mechanism?
Decouple the queuing of emails from sending them. e.g.:
Create a database table for outgoing emails, with a column for their Sent date.
Whenever you want to send an outgoing email, insert it into the table with a NULL sent date.
Have a background task run every X seconds to check for emails with a NULL sent date, try sending them, and update their Sent date if successful. HINT: for an easy way to queue recurring tasks in ASP.NET have a look at this.
This is a very stripped to bone simple example, but you can easily expand on it.
I want to send mail from my website domain(www.sample.com)
I have written below code. It is not returning any error. But it is not sending mail once I uploaded the pages in the server. Once click on email send, it is not getting any error, but not receiving the mail.
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("mail.sample.co.uk", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("smtpuser#sample.co.uk", "pass#123");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = false;
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
//Setting From , To and CC
mail.From = new System.Net.Mail.MailAddress("smtpuser#sample.co.uk", "MyWeb Site");
mail.To.Add(new System.Net.Mail.MailAddress("myemail#gmail.com"));
mail.CC.Add(new System.Net.Mail.MailAddress("myemail1#gmail.com"));
smtpClient.Send(mail);
I am getting the "mailsend" response text in the page once calling the sending method.
Please help
Anjana
The following code works perfect for me. Make sure you have added a mail account on the smtp server and activated it.
private static string EMAIL_SERVER = "mailservername.mydomain.com";
private static string EMAIL_NAME = "myMailAccount#mydomain.com";
private static string EMAIL_PASSWORD = "complex_password123";
private static string EMAIL_SEND_TO = "sample#mail.com";
protected string SendMail()
{
try
{
System.Net.Mail.MailMessage objMM = new System.Net.Mail.MailMessage();
objMM.From = new MailAddress("fromMe#mail.com", "john doe");
objMM.To.Add(new MailAddress(EMAIL_SEND_TO)); //Note: this To a collection
objMM.Subject = "Subject1";
objMM.Body = "Hello world this is my text";
objMM.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(EMAIL_SERVER);
smtp.Credentials = new NetworkCredential(EMAIL_NAME, EMAIL_PASSWORD);
smtp.Send(objMM);
}
catch (Exception e)
{
return "Message can not be send couse of error: " + e.ToString();
}
return "Message is send.";
}
I have functionality in my site which sends a email to an id .. Email contains a link to a webpage and a security key .. But the problem is it goes into the junk folder
I'm using free hosting by Somee.com
Code:
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.Body = ("Copy The Link And paste It In Them follow Link Download </br>"+ encoded_url);
message.From = new MailAddress("lz-wag#hotmail.com");
message.To.Add(TextBox2.Text);
message.Subject = user + " Has Share The File With You";
try{
SmtpClient client = new SmtpClient();
client.Host = "smtp.live.com";
client.EnableSsl = true;
System.Net.NetworkCredential networkcred = new System.Net.NetworkCredential();
networkcred.UserName = "lz-wag#hotmail.com";
networkcred.Password = "password";
client.Port = 587;
client.Credentials = networkcred;
client.Send(message);
sendFile.Visible = false;
Label1.Visible = true;
Label1.Text = "Your File Has Been Shared";
}
catch(Exception ex){
Label1.Visible = true;
Label1.Text = "Your File Is Not Shared";
//Label1.Text = ex.ToString(); ;
}
Whether or not the email goes into the junk mail folder is a function of the email client, not a function of how you are sending the email.
However, FYI, both the MailMessage and the SmtpClient implement IDisposable, so should be in using blocks. Something like this:
using (MailMessage message = new MailMessage())
{
// ...
using (SmtpClient client = new SmtpClient())
{
// ...
client.Send(message);
}
}
I also suggest that you log the exception somewhere, or you'll never know what went wrong when something goes wrong.