how to protect classify sent emails as spam in asp.net [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I lower the spam score of my email message?
I have this c# code that can send lots of emails to people . but emails that I sent has classified as spam .what should I do .is there any change that I should apply to my code?I try to get email addresses from sql server data base .and My code can attach one file .
Entities context = new Entities();
var query = from c in context.Emails select c.EmailAddress;
MailMessage mail = new MailMessage();
Regex sample = new Regex(#"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*
#[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
int total = 0;//number of all emails
int count = 0;//counter for putting interrupt between each 10 sending
int failed = 0;//number of failed sending
int success = 0;//number of successful sending
double totalsize = 0;//size of attachment file
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
foreach (Attachment attachment in mail.Attachments)
{
string size =attachment.ContentStream.Length.ToString ();
totalsize=Convert .ToDouble (size);
}
}
foreach (var c in query)
{
if (count == 10)
{
Thread.Sleep(10000);
count = 0;
}
mail.From = new MailAddress("hadi#myhost.com");
mail.Bcc.Add(new MailAddress(c.ToString()));
mail.Subject = "hello";
mail.IsBodyHtml = true;
mail.Body = FCKeditor1.Value.ToString();
SmtpClient smtp = new SmtpClient();
smtp.Host = "localhost";
smtp.Port = 25;
if ((sample.IsMatch(c.ToString())) && (sample .IsMatch (mail .From .ToString ())) && (totalsize<1000000))
{
try
{
smtp.Send(mail);
//Response.Write("email has sent to " + c.ToString());
success++;
}
catch
{
//Response.Write("email has not sent to " + c.ToString());
failed++;
}
count++;
}
total++;
}

You don't have to do anything with your code to make it not spam. All you have to do is to make sure you are sending email from a host that should not have "Open Relay" means not everybody can send email from it.
Send your email from proper server and with proper email signature , so that when receiver checks back for authentication they should authenticate your email source server and signature validated from your email host.

Related

How to send logged email using smtp in c#?

I wanted to know how I can send a logged email (visible in sent items) via smtp in c#.
Model I'm using :
try
{
SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
string from = "myemail#gmail.com";
string to = "reciever#gmail.com";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Enter the subject here";
msg.Body = "The message goes here.";
msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email. Error : " + ex);
}
But i can't see it in sent mails.
Short answer: You can't.
The only way to add the message to your Sent folder is to specifically add it there yourself using the IMAP protocol (or via a library that implements the IMAP protocol).

How can I send email to multiple recipients from SQL Server database in ASP.NET MVC?

I want to send email to multiple recipients. I retrieve the email addresses of multiple users from a SQL Server database, like this:
var students = (from u in db.Users
where u.projectGroup == id
select u.userEmail).ToArray();
This will return multiple email addresses like: user1#gmail.com user2#gmail.com
and I try to send to multiple users like this
for (int h = 0; h < students.Length; h++)
{
try
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var smtpClient = new SmtpClient();
var message = new MailMessage();
message.To.Add(new MailAddress(students[h]));
message.Subject = "I'm interested in your project";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
return RedirectToAction("Sent");
}
}
catch (Exception ex)
{
//MessageBox("Your Email address is not valid");
//ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Your Email address is not valid');", true);
}
}
but this did not work, it sends an email to first user but another user did not receive the email.
How can I split each email in a one row to send an email to multiple recipients?
Everything seems to be good. However, your redirectToAction is executing for the first email and comes out of loop.After that control doesn't know how to continue for second record. that's why your email wont be sent to second email. try below code you should be good.
for (var index= 0; index< students.Length; index++)
{
try
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var smtpClient = new SmtpClient();
var message = new MailMessage();
message.To.Add(new MailAddress(students[index]));
message.Subject = "I'm interested in your project";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
}
}
catch (Exception ex)
{
//MessageBox("Your Email address is not valid");
//ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Your Email address is not valid');", true);
}
}
return RedirectToAction("Sent");
return RedirectToAction("Sent"); is the culprit.
This will stop your code after the first email. Don't return from your method until they've all been sent:
using (var smtp = new SmtpClient())
{
for (int h = 0; h < students.Length; h++)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress(students[h]));
message.Subject = "I'm interested in your project";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
message.IsBodyHtml = true;
smtp.Send(message);
}
}
return RedirectToAction("Sent");
N.B. I also removed the redundant try/catch (don't use it if you're not going to log the exception (although you should do that globally anyway), suppressing unexpected errors is an anti-pattern) and reduced the number of times you unnecessarily instantiate a brand new SmtpClient - it's fine to use the same one each time. Also, if you're going to await the async email call, there's no point using it - just use the regular Send instead.
You are returning SENT from inside your loop, so it does the first item then exits.

Optimize using SMTP to send messages

I have an application that sends emails via SMTP, however it is slower than sin. Two recipients can take over 20 seconds. I believe the problem is the program logic.
The program opens a csv with email addresses and display names then using a for loop sends each recipient the message.
The problem is, I fear it is re-establishing SMTP connection every time it sends to the next person in the list.
My question is, how do I setup an SMTP connection and reuse that connection for every user? (unless that's not why its slow, and someone can tell me why its running so slow)
void DoWork(object sender, DoWorkEventArgs e)
{
// Get User List
List<string[]> mycsv = csvRead();
int total = mycsv.Count;
// Send Message to each user
for (int x = 0; x < total; x++)
{
//Actual send message
sendMail(mycsv[x][0], mycsv[x][1]);
}
}
private void sendMail(string toEmail, string toName)
{
string email = Properties.SMTP.Default.Email;
string name = Properties.SMTP.Default.DisplayName;
MailMessage mail = new MailMessage();
mail.From = new MailAddress(email, name);
//Recipient Address
mail.To.Add(new MailAddress(toEmail, toName));
//Formatted mail
mail.IsBodyHtml = true;
// htmlMessage and Subject are global
mail.Body = htmlMessage;
mail.Subject = htmlSubject;
SmtpClient smtp = smtpDetails();
smtp.Send(mail);
}
private SmtpClient smtpDetails()
{
int port = Convert.ToInt32(Properties.SMTP.Default.ServerPort);
string email = Properties.SMTP.Default.Email;
string username = Properties.SMTP.Default.Username;
string password = Properties.SMTP.Default.Password;
string host = Properties.SMTP.Default.ServerAdd;
SmtpClient smtp = new SmtpClient();
smtp.Port = port;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(username, password);
smtp.Host = host;
return smtp;
}
VS: 2013 - 4.5 .net - WPF app
One way to improve the speed could be to make a static class for the mail delivery. Eg. a mail handler class with the static method SendMail (where you put your smtpDetails() into.
So there won't be a need to create new instances of the SmtpClient for every call in the loop - just reuse the static method.
You could also use a using:
using(SmtpClient smtp = new SmtpClient())
{
Port = port
//etc
}
This will dispose of all your smtp connections.

sending mail failure in asp.net using c# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending email in .NET through Gmail
This mail code is working in localhost i.e on my computer but when i uopload it on server it is not working.
The error is : Failure sending mail. please tell me where is the problem.
if (Session["userinfo"] != null)
{
lblTest.Text = Session["userinfo"].ToString();
MailMessage msg = new MailMessage();
msg.From = new MailAddress("shop.bcharya#gmail.com");
msg.To.Add(new MailAddress("bcc#dr.com"));
msg.To.Add(new MailAddress("info#yzentech.com"));
msg.Subject = "Mail from BcharyaCorporation.online shopping site";
msg.Body = ""+lblTest.Text+" wants to buy some products. please contact with him/her";
SmtpClient sc = new SmtpClient();
sc.Host = "smtp.gmail.com";
// sc.Port = 25;
sc.Credentials = new NetworkCredential("shop.bcharya#gmail.com", "mypassword");
sc.EnableSsl = true;
try
{
sc.Send(msg);
lblPayment.Text = "Sorry. Currently we are out of online payment service. We will contact you for payment process. Thank you for buying this product.";
}
catch (Exception ex)
{
lblPayment.Text=ex.Message.ToString();
Response.Write(ex.Message);
}
}
For gmail mail settings add Port number too
sc.Port = 587;
after this line
sc.Host = "smtp.gmail.com";
Only use port 587 and SSL if the SMTP server supports that (GMail and Hotmail for example). Some servers just use port 25 and no SSL.
Use below method and then check :
SmtpClient sc = new SmtpClient(string); //sends e-mail by using the specified SMTP server
You can use this below given code for sending email. Here sending the error details through email is one method. Try this code for sending email.
using System.Web.Mail
public static bool SendErrorEmail(string to, string cc, string bcc, string subject, string body, MailPriority priority, bool isHtml)
{
try
{
using (SmtpClient smtpClient = new SmtpClient())
{
using (MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress(“yourmail#domain.com”, “Your name”);
// You can specify the host name or ipaddress of your server
smtpClient.Host = “mail.yourdomain.com”; //you can specify mail server IP address here
//Default port is 25
smtpClient.Port = 25;
NetworkCredential info = new NetworkCredential(“yourmail#domain.com”, “your password”);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = info;
//From address will be given as a MailAddress Object
message.From = from;
message.Priority = priority;
// To address collection of MailAddress
message.To.Add(to);
message.Subject = subject;
// CC and BCC optional
if (cc.Length > 0)
{
message.CC.Add(cc);
}
if (bcc.Length > 0)
{
message.Bcc.Add(bcc);
}
//Body can be Html or text format;Specify true if it is html message
message.IsBodyHtml = isHtml;
// Message body content
message.Body = body;
// Send SMTP mail
smtpClient.Send(message);
}
}
return true;
}
catch (Exception ee)
{
Logger.LogError(ee, “Error while sending email to ” + toAddress);
throw;
}
}

Email From ASP.net is going as HTML attachment

As the title says, I am sending email from my ASP.net web application without any attachment (for now) but strangely the body of email is going as a separate HTML file attached to blank email like when I click the HTML file it opens the body in separate window with everything that I have written in body as standalone HTML file, this is only happening when I send email to some portals like e-lance but when I send it to gmail or hotmail address then email is going perfectly with no attachment and body-text appearing where it should.
My email code is
public bool sendMail(string messageSubject, System.Net.Mail.MailAddress fromEmailAddress, System.Net.Mail.MailAddress toEmailAddress, string source_id, string messageText)
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.IsBodyHtml = true;
mail.Subject = messageSubject;
mail.From = fromEmailAddress;
mail.To.Add(toEmailAddress);
mail.Body = messageText;
SmtpClient relayServer = new SmtpClient();
List<KeyValuePair<string, string>> commandParameters = new List<KeyValuePair<string,string>>();
commandParameters.Add(new KeyValuePair<string,string>("#source_id", source_id));
DataTable sourcesTable = SQLSelect("SELECT * FROM LogiCrmSources WHERE source_id = #source_id", commandParameters);
relayServer.Host = sourcesTable.Rows[0]["source_smtp"].ToString();
relayServer.Port = Convert.ToInt16(sourcesTable.Rows[0]["source_smtp_port"].ToString());
if (relayServer.Port == 25)
{
relayServer.EnableSsl = false;
}
else
{
relayServer.EnableSsl = true;
}
relayServer.Credentials = new System.Net.NetworkCredential(sourcesTable.Rows[0]["source_email"].ToString(), sourcesTable.Rows[0]["source_password"].ToString());
try
{
relayServer.Send(mail);
return true;
}
catch(SmtpFailedRecipientException exp)
{
return false;
}
}
Not all clients can handle html emails properly. Gmail for example can while the portals you mention can't. In those cases the body of the email as sent as an attachment.

Categories

Resources