Email messages going to spam folder - c#

I have created a community portal, in which user creates his/her account. After successfull registration a confirmation mail is send on registered email address.
I am using the following code to send the mail -
private void SendMail(string recvr, string recvrName, string verCode, int NewUserID)
{
try
{
string emailID = ConfigurationManager.AppSettings["WebMasterMail"];
string mailPass = ConfigurationManager.AppSettings["pass"];
string mailer = ConfigurationManager.AppSettings["mailer"];
MailMessage msg = new MailMessage();
MailAddress addrFrom = new MailAddress(emailID, "Panbeli.in.... Bari community portal");
MailAddress addrTo = new MailAddress(recvr, recvrName);
msg.To.Add(addrTo);
msg.From = addrFrom;
msg.Subject = "You have registered sucessfully on PanBeli.in.";
msg.Priority = MailPriority.High;
msg.Body = RegisterMessageBody(recvrName, verCode,NewUserID);
msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(mailer);
smtp.Credentials = new System.Net.NetworkCredential(emailID, mailPass);
smtp.Send(msg);
}
catch (Exception Ex) { }
}
While testing we found that all the confirmation mails are going to SPAM folder instead of Inbox.
Is there anything wrong with the code or is there anything related to security.
Can anybody suggest solution to this problem.
Thanks for sharing your time.

It sounds like your email is getting flagged by SpamAssassin or the like, so you just need to focus on changing your email enough to not get flagged.
Your content doesn't sound like it has any reason to rate high for the Bayesian score, so I don't think thats the problem. It wouldn't hurt to try removing possible trigger words though.
Your message is marked with high priority. Do you need this? This just adds into one of the scoring metrics in a spam filter. Spam is often marked with high priority, so your message will be treated with more scrutiny. On the otherhand, for some filters marking your message with high priority will mean less scrutiny.
IsBodyHTML is marked true, but you're only providing text/html. You minimally need to include an alternate view with text/plain.
message.IsBodyHtml = true;
string html = RegisterMessageBodyHtml(recvrName, verCode,NewUserID);
string plain = RegisterMessageBodyPlaintext(recvrName, verCode, NewUserID);
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, new ContentType("text/html"));
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plain, new ContentType("text/plain"));
See how Google treats your message. In gmail, open a test message that you've sent, click the downfacing arrow next to the reply button, and select "Show Original". You'll see how Google treated your message. Look for headers like:
Received-SPF: softfail (google.com: domain of transitioning xxx#xxx.org does not designate xx.xx.xx.xx as permitted sender) client-ip=xx.xx.xx.xx;
Authentication-Results: mx.google.com; spf=softfail (google.com: domain of transitioning xxx#xxx.org does not designate xx.xx.xx.xx as permitted sender)
Read up on the default rule set for SpamAssassin as it will probably be a good reference on the rule sets for most filters. If you can identify why your message is getting flagged, you can fix it.

Emails Marked as Spam
This is not a programming issue unfortunately, but I can understand why you might think it is. The code is sending the emails, and they have been sent as you reported. So this is highly unlikely to be a problem with your code, because it's served it's purpose fully!
Getting around it
It all comes down to the recipients mail client (the software they are using to view the emails with), or the services that process the emails at some sort of gateway, or a combination of both of these!
All of these elements have vastly varied algorithms and metrics for determining if an email is probably spam or not. So a one fit all solution is sadly not possible. Some are intelligent, other less so, some brutally discard a huge % of emails, others operate purely on a 'not on white list, you're not getting in' policy, and then there are those that just let everything come in regardless of content/origin.
The ways to go around fixing this are:
To try and get on white lists for major email providers.
Educate your audience to add the senders email address as a trusted contact.
Check your mail server IP isn't blacklisted by some providers. It's possible your IP address was previously used to send spam.
Experiment with the emails content

Your from address is invalid. Try putting in a real email address that points to a valid mailbox. Preferably this email address is on the same domain as the SMTP server you use to send the mail with. If not, read into SPF http://en.wikipedia.org/wiki/Sender_Policy_Framework

This happen to me to and it's solved now,
I just set the BodyEncoding and SubjectEncoding proprieties on the MailMessage object,
and added the DOCTYPE and the html tags to my email header,
var msg = new MailMessage
{
Subject = subject,
Body = body,
BodyEncoding = System.Text.Encoding.UTF8,
SubjectEncoding = System.Text.Encoding.Default,
IsBodyHtml = true
};
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
It's working perfectly now

Add following line in your code while creating MailMessage
msg.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");

This happens a lot even for the house hold names. I sympathise with you as you only want a plain text email but if your clients really want those emails and you really want your logo in then they could just white list your domain so that all emails get through!
We use a company called mailchimp for sending out subscriber mails and I questioned them on how to avoid spam filters especially in the context of essentially an advert out to a large group it can be very difficult to avoid them, here is their advice and there is lots of it.;
Avoiding the Spam Filters

For anyone having this problem, it looks like Google mark as spam any mails using the default ASP.NET e-mail authentication subject and body. I.e.:
"Please confirm your account by clicking here."
Changing the text allows the e-mail to pass the spam filter

Related

Sending emails as company domain from SendGrid

I own a domain, example.com. I'd like to send out emails from my webapp where it displays it's from info#example.com, or support#example.com.
I've used SendGrid a lot in the past from within my websites, but I've always simply been able to fill out where an email is from by editing the From property of the SendGridMessage class, and it just showed up that way on clients.
Is there an official way/API from sendgrid to utilize a domain that I own? What's to stop me or someone else from typing any domain they want using the sendgrid API?
The process of setting up DNS records for your domain that allow your emails to be authenticated, as well as verifying your ownership of the domains, is known at SendGrid as whitelabeling. After this process, SPF and DKIM records will then be available for receiving servers to check.
SPF and DKIM ensure the originating IP is allowed to send email on behalf of the domain in question, and to essentially verify that the contents of the email have not been tampered with respectively.
The thing that will stop others from sending from your domain is called DMARC. Domains owned by yahoo, aol, and very soon google all implement strict policies; emails claiming to be from these domains but that are not will never be delivered. Many other domains will soon be following this trend and implementing DMARC.
The code sample from https://azure.microsoft.com/en-us/documentation/articles/sendgrid-dotnet-how-to-send-email/ shows how to do this:
// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();
// Add the message properties.
myMessage.From = new MailAddress("john#example.com");
// Add multiple addresses to the To field.
List<String> recipients = new List<String>
{
#"Jeff Smith <jeff#example.com>",
#"Anna Lidman <anna#example.com>",
#"Peter Saddow <peter#example.com>"
};
myMessage.AddTo(recipients);
myMessage.Subject = "Testing the SendGrid Library";
//Add the HTML and Text bodies
myMessage.Html = "<p>Hello World!</p>";
myMessage.Text = "Hello World plain text!";

Web Server is Sending Duplicate E-Mails

For every e-mails that my website sends I have it send myself an email as well. I noticed that about 5% of the e-mails (Thousands a day) are being sent twice. The time between the duplicates being sent however is completely inconsistent...Can be a week, a month or a minute. Completely inconsistent...I've tried to debug the issue but I can never duplicate the issue. Always just sends one e-mail and works properly. I'm out of ideas so decided to try and gain some input form the community. Any insight would be greatly appreciated...
public static void SendEmail(string subject, string body, string toAddress, string fromAddress)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(fromAddress);
msg.To.Add(new MailAddress(toAddress));
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = false;
using (SmtpClient cli = new SmtpClient())
{
cli.Send(msg);
cli.Dispose();
}
}
Dispose() was just one of my recent attempts that have failed to fix the problem....
And the ascx page that calls the function (note that it is called twice to send it to myslef the first time and the customer the second time if there e-mail address is not null. I did this during testing and decided to leave it in there:
Txp.SendEmail(strOrderConfirmationHeader, strOrderConfirmationText, TxpConst.ORDERNOTIFYADDR, TxpConst.RETURNADDR);
if (!String.IsNullOrWhiteSpace(custemail))
{
Txp.SendEmail(strOrderConfirmationHeader, strOrderConfirmationText, custemail, TxpConst.RETURNADDR);
}
The fact that it's so inconsistent tells me it's probably not the code and it's not the e-mail server cause the mail logs show a completed transaction every time and it gets a different message id every time...I'm all out of ideas!
OK, I'm sure you've already considered this, but are you sure your visitor isn't hitting "submit" twice?
I've seen this many times, particularly when the email server is running a little slowly. User thinks the site isn't doing anything so clicks Submit again. (Or they just double-click the button - seen that too!)
You might just need to put some code your app to guard against multiple submission. It's a fairly common issue.
Hope this helps you.

how to send email in C# even when one of the recipient is invalid?

I am trying to send email to multiple recipients and it works fine when all the recipients have valid email address.
But when one of the recipients have invalid email address, email is not sent even to other recipients whose email address is valid and I am getting an exception:
The server rejected one or more recipient addresses. The server
response was: 550 #5.1.0 Address rejected.
Is there any way I can send the email to other valid recipients even if one of the email address is invalid?
public static void sendMails(string ptxtSubject, string ptxtBody)
{
string txtTo = "valid1#aaa.com,valid2#aaa.com,invalid1#aaa.com";
string txtFrom = "valid#aaa.com";
string txtSubject = ptxtSubject;
string txtBody = ptxtBody;
MailMessage mail = new MailMessage();
mail.To = txtTo;
mail.From = txtFrom;
mail.Subject = txtSubject;
mail.Body = txtBody;
try
{
SmtpMail.SmtpServer ="smtp.aaa.com";
SmtpMail.Send(mail);
}
catch (Exception ex)
{
//log the exception
throw;
}
}
I can send separate mail to each of them but users(recipients) will not know who else is in the email distribution list. My requirement is everyone should be able to know who else is receiving the email.
Outlook sends the email to all the valid users and notifies us back of invalid users. Is there anyway we can do the same using C#?
Unless all the recipients definitely know each other (and they don't mind other people knowing they are receiving email from you), you should be sending separate emails anyway.
This would also take care of your problem, i.e. if one send operation fails, it won't disrupt the others. Note that in your case, it appears that the initial relay is failing because the addresses are from the same host as the SMTP server.
Once an email is routed to multiple hosts, the success/failure is no longer interdependent. For example, a gmail.com server probably doesn't know/care that a yahoo.com server rejected a recipient.
If performance is a concern, you can send the messages asynchronously to get achieve better throughput. Note that you can still handle exceptions when sending asynchronously.
As always, if you are sending any quantity of email, it's probably advisable to use a 3rd party service.
I really don't see any way to accomplish this. Sending an email with SmtpMail.Send() is pretty much an atomic function and you need correct data for it to work without an exception.
The only option I see here is to send separate emails to each recipient.

How to put contact us page in windows application c# [duplicate]

I'm thinking of implementing "Report a bug/Suggestions" option to my game, however I am not quite sure how I could get that working. I do not have my own server or anything, so I can't just send the text that user has written to there.
The only way I came up with is that the client would write a message and I would send it to an email account where I could read them. However, I do not want that users would need to send the reports through their personal accounts. I am not quite sure how I could implement this and googling didn't bring up any good suggestions.
I haven't done a lot of network stuff, so I'd really appreciate it if you could explain ( possibly even in code ) the process step-by-step.
I am using C# and the game is being programmed for Windows Phone 7.
Yes, it is absolutely possible to do that. From a relatively low-level perspective, you need to:
Resolve the MX (mail-exchanger) server for the e-mail account you want to send to.
Open a socket to the MX server.
Send the appropriate SMTP commands to cause the e-mail message to be delivered to your recipient account. You essentially have the freedom to set the "from" address to be any arbitrary thing you want.
SMTP is a very simple/human-friendly protocol, so it's not a massive effort to do all of that by hand. At the same time, there are prebuilt libraries that will handle all of that for you (except possibly the resolution of the recipient's MX server).
Note that emails sent this way are more likely to be filtered out as spam (generally because the sender's IP/hostname is not going to match whatever domain you put on the outgoing e-mail address you decide to use).
Also note that since you can set the "from" address to anything, you have the option of asking the user if they want to provide their actual contact address, and if they do you can make that the "from" address so that you can actually get back in touch with them if necessary.
You don't need to use email at all. Consider using an error reporting service like sentry or airbrake.
These services have clients that you embed in your program; which automatically log your errors, including any debugging information/stacktrace; and notify you by email when your application reports a problem.
Usually you integrate the app's API into your own error handling mechanism. At the point of an error, the client will capture your debugging information, you can popup a modal asking user for information like "what were you doing when this error happened?", save that as part of your error response that is sent back to the service.
Since the app works over HTTP, you don't need any special ports to be open. It is easier and more helpful than having users send you emails with "it doesn't work!!", and you don't have to deal with email sending headaches.
I recently wrote an article on this: Sending email with C#
You basically have two choices, either you send it using an SMTP-client, this means that you have to have a SMTP-server and be able to connect to port 25 (if you're not using an external SMTP, then you have to manage that by yourself). Or you can use an external email provider, such as:
AlphaMail
SendGrid
Mandrill
If you're using AlphaMail you can send emails in the following way:
IEmailService emailService = new AlphaMailEmailService()
.SetServiceUrl("http://api.amail.io/v1/")
.SetApiToken("YOUR-ACCOUNT-API-TOKEN-HERE");
var person = new Person()
{
Id = 1234,
UserName = "jdoe78",
FirstName = "John",
LastName = "Doe",
DateOfBirth = 1978
};
var response = emailService.Queue(new EmailMessagePayload()
.SetProjectId(12345) // ID of AlphaMail project (determines options, template, etc)
.SetSender(new EmailContact("support#company.com", "from#example.com"))
.SetReceiver(new EmailContact("Joe E. Receiver", "to#example.org"))
.SetBodyObject(person) // Any serializable object
);
Another thing that differs from just building HTML and sending it with an SMTP-client is that with AlphaMail you have the ability to edit your emails outside your code directly in a GUI. You can also easily create highly dynamic templates using AlphaMail's templating language Comlang.
<html>
<body>
<b>Name:</b> <# payload.FirstName " " payload.LastName #><br>
<b>Date of Birth:</b> <# payload.DateOfBirth #><br>
<# if (payload.Id != null) { #>
Sign Up Free!
<# } else { #>
Sign In
<# } #>
</body>
</html>
So this is my thought, why don't you have the email sent to you...as you?
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name"); //Both the email addresses would be yours
var toAddress = new MailAddress("to#example.com", "To Name"); //Both the email addresses would be yours
const string fromPassword = "fromPassword";
const string subject = "There name or whatever";
const string body = "Errors ect....";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
code from here
All they would see would be the submit button so they wouldn't have all your personal username/password, also you should prolly set up a dummy account to have them sent to even if it just then forwards them to your real email account.
Another way to achieve this would be to host a WCF Service which takes in your Message and stores in db or /sends email. One downside of this is you'll need a web server to do this.
Try following code this might help you :
Dim objCDOMail
Set objCDOMail = Server.CreateObject("CDONTS.NewMail")
objCDOMail.From = "sender#domain.com"
objCDOMail.To = "receiver#domain.com"
objCDOMail.Subject = "Test Mail Script"
objCDOMail.BodyFormat = 0
objCDOMail.MailFormat = 0
objCDOMail.Body = "Testing Mail from Test Script"
objCDOMail.Importance = 1
objCDOMail.Send
Set objCDOMail = Nothing

C# Send both HTML and Text email - most elegant?

Is it best practice to send both HTML and Text email?
If I only send HTML what are the dangers?
I'm thinking something like this below, from http://johnnycoder.com/blog/2009/04/15/net-mailmessage-linkedresources-alternateviews-and-exceptions/.
try
{
// Assign a sender, recipient and subject to new mail message
MailAddress sender =
new MailAddress("sender#johnnycoder.com", "Sender");
MailAddress recipient =
new MailAddress("recipient#johnnycoder.com", "Recipient");
MailMessage m = new MailMessage(sender, recipient);
m.Subject = "Test Message";
// Define the plain text alternate view and add to message
string plainTextBody =
"You must use an email client that supports HTML messages";
AlternateView plainTextView =
AlternateView.CreateAlternateViewFromString(
plainTextBody, null, MediaTypeNames.Text.Plain);
m.AlternateViews.Add(plainTextView);
// Define the html alternate view with embedded image and
// add to message. To reference images attached as linked
// resources from your HTML message body, use "cid:contentID"
// in the <img> tag...
string htmlBody =
"<html><body><h1>Picture</h1><br>" +
"<img src=\"cid:SampleImage\"></body></html>";
AlternateView htmlView =
AlternateView.CreateAlternateViewFromString(
htmlBody, null, MediaTypeNames.Text.Html);
// ...and then define the actual LinkedResource matching the
// ContentID property as found in the image tag. In this case,
// the HTML message includes the tag
// <img src=\"cid:SampleImage\"> and the following
// LinkedResource.ContentId is set to "SampleImage"
LinkedResource sampleImage =
new LinkedResource("sample.jpg",
MediaTypeNames.Image.Jpeg);
sampleImage.ContentId = "SampleImage";
htmlView.LinkedResources.Add(sampleImage);
m.AlternateViews.Add(htmlView);
// Finally, configure smtp or alternatively use the
// system.net mailSettings
SmtpClient smtp = new SmtpClient
{
Host = "smtp.example.com",
UseDefaultCredentials = false,
Credentials =
new NetworkCredential("username", "password")
};
//<system.net>
// <mailSettings>
// <smtp deliveryMethod="Network">
// <network host="smtp.example.com"
// port="25" defaultCredentials="true"/>
// </smtp>
// </mailSettings>
//</system.net>
smtp.Send(m);
}
catch (ArgumentException)
{
throw new
ArgumentException("Undefined sender and/or recipient.");
}
catch (FormatException)
{
throw new
FormatException("Invalid sender and/or recipient.");
}
catch (InvalidOperationException)
{
throw new
InvalidOperationException("Undefined SMTP server.");
}
catch (SmtpFailedRecipientException)
{
throw new SmtpFailedRecipientException(
"The mail server says that there is no mailbox for recipient");
}
catch (SmtpException ex)
{
// Invalid hostnames result in a WebException InnerException that
// provides a more descriptive error, so get the base exception
Exception inner = ex.GetBaseException();
throw new SmtpException("Could not send message: " + inner.Message);
}
I would say that, in today's world, the "best-practice" approach would be to ensure that you send your message as both plain text and HTML (if you really want to send HTML email messages).
Oh, and make sure you do actually send the content in the plain text view, rather than a single sentence saying "You must use an email client that supports HTML messages". Google Mail takes this approach, and it seems to work perfectly, allowing "rich" views on full-fledged PC clients, whilst also allowing "minimal" views on more restricted devices (i.e. Mobile/Cell phones).
If you want to take a purist's view, you wouldn't be sending HTML emails at all, nor would you ever "attach" a binary file to an email. Both corruptions of the original email standard, which was only ever originally intended for plain text.
(See some people's opinions of this here and here)
However, in the pragmatic modern-day real world, HTML email is very real, and very acceptable. The primary downside to sending HTML email is whether the recipient will see the email in the way that you intended them to see it. This is much the same problem that web designers have battled with for years; getting their websites to look "just right" in all possible browsers (although it's significantly easier today than it was many years ago).
Similar to ensuring that a website functions correctly without requiring Javascript, by sending your emails as both HTML and Plain Text, you'll ensure that your emails degrade gracefully so that people reading their emails on (for example) small mobile devices (something that's becoming more and more prevalent these days - and which may or may not be capable of rendering a complete HTML email) can still read your email content without issue.
If you only send HTML, then anyone reading email on a text-only device will have trouble.
For example, I suspect many low-end mobile devices are capable of reading email but not displaying full HTML.
I would say it's best practice to either send text-only, or text and HTML.
I don't see why you're catching a bunch of exceptions only to rethrow the same exception type with a different message, by the way - the original message may well be more descriptive.
Another reason to send both is that many mailservers mark emails that only contain HTML content as spam. You don't want all your emails to be put in the junk folder.
I think yes, the best practice is to send both. The reason (c&p from wikipedia):
The default e-mail format according to RFC 2822 is plain text. Thus
e-mail software isn't required to support HTML formatting. Sending
HTML formatted e-mails can therefore lead to problems at the
recipient's end if it's one of those clients that don't support it. In
the worst case, the recipient will see the HTML code instead of the
intended message.
Sharing my experience with sending both HTML and text in one email:
I have created an email message that has 2 views: text and html using C# AlternateView classes.
What did I get?
On Mac, tested on High Sierra:
Apple Mail app was showing the Html. If the order of messages is reversed: Html - text then Apple Mail will show the text view. The conclusion: Apple Mail is using the last view as default.
In Windows, Outlook 2010:
Microsoft Outlook by default is using the Html view. The order of views in the email doesn't matter: html,text; text,html;
If for some reason you selected a setting to show incoming messages as a text then the Html version of your email will be converted into the text by Outlook.
Even so you send the text version of your email (which might be slightly different from the HTML version and was formatted to look pretty) it won't be used.
So you don't need to send the text version of your email if you know that your clients use Outlook and Html version is selected as default.
Mozilla Thunderbird respects your settings and shows the correct Html or text version of your email. It works correctly on Mac and in Windows
Hope it helps
Several email clients will use the last AlternateView that was added to the AlternateViews.
So if you prefer to have your mail displayed as HTML, be sure to add that last.
I have notice this for IOS mail and OSX mail, while Android Email seems to prefer HTML if it is available. I am not sure for which versions this holds, and the behaviour is often user-configurable, but in my experience these were the defaults.

Categories