When I want to send message to outlook.com e-mail address, then it's going to spam/junk folder, while it's OK for Google and Yahoo mail. I've checked SpamAssassin scores for all these mail providers (I've used https://spamcheck.postmarkapp.com/):
Google: 1.7, Good
1.5 RCVD_IN_SORBS_WEB (I'm on one blacklist)
Yahoo: 1.5, Good
1.5 RCVD_IN_SORBS_WEB (the same - I'm on one blacklist. The rest is OK!)
Outlook: 5.7, Spam!
0.0 URIBL_BLOCKED ADMINISTRATOR NOTICE: The query to URIBL was
blocked. See
http://wiki.apache.org/spamassassin/DnsBlocklists…
#dnsbl-block for more information. [URIs:x]
1.2 MISSING_HEADERS Missing To: header
0.1 DKIM_SIGNED Message has a DKIM or DK signature, not
necessarily valid
0.1 DKIM_INVALID DKIM or DK signature exists, but is not valid
0.0 UNPARSEABLE_RELAY Informational: message has unparseable relay lines
1.4 MISSING_DATE Missing Date: header
1.0 MISSING_FROM Missing From: header
0.1 MISSING_MID Missing Message-Id: header
1.8 MISSING_SUBJECT Missing Subject: header
0.0 TVD_SPACE_RATIO No description available.
GMX: 4, Good (well, it's in spam folder!)
-0.0 RCVD_IN_DNSWL_NONE RBL: Sender listed at https://www.dnswl.org/, no
trust [ listed in list.dnswl.org]
0.1 DKIM_SIGNED Message has a DKIM or DK signature, not
necessarily valid
0.1 DKIM_INVALID DKIM or DK signature exists, but is not valid
1.3 RDNS_NONE Delivered to internal network by a host with no
rDNS
2.3 EMPTY_MESSAGE Message appears to have no textual parts and no
Subject: text
0.1 MISSING_MID Missing Message-Id: header
As you can see there're missing headers, but it was OK in Google and Yahoo. Here is my code (C#)
MailMessage mail = new MailMessage(username, mailReceiver);
mail.Subject = title;
AddAlternativeTextViewToMail(ref mail, message); // adding alternative view to HTML one (plain text)
SmtpClient client = new SmtpClient();
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
mail.IsBodyHtml = true;
mail.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.UseDefaultCredentials = false;
client.Host = "mail.mydomain.com";
client.Credentials = new NetworkCredential(username, password);
//mail.Body = message; // no body, coz it's already in alternative view
client.Send(mail);
Here is AddAlternativeTextViewToMail method:
private static void AddAlternativeTextViewToMail(ref MailMessage mail, string message)
{
string htmlTagPattern = "<[^\"]*?>";
string plainMessage = message.Replace("<br />", "\r\n");
plainMessage = Regex.Replace(plainMessage, htmlTagPattern, string.Empty);
plainMessage = plainMessage.Replace("<", "").Replace(">", "").Replace("a target=\"_blank\" href=\"", " ").Replace("\"", " ").Replace("a href=", "");
//plainMessage = Regex.Replace(plainMessage, #"^\s+$[\r\n]*", "", RegexOptions.Multiline);
//plainMessage = plainMessage.Replace(" ", string.Empty);
mail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainMessage, Encoding.UTF8, System.Net.Mime.MediaTypeNames.Text.Plain));
mail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(message, Encoding.UTF8, System.Net.Mime.MediaTypeNames.Text.Html));
}
Also if I send the same e-mail from Google mail, then it is not going to spam folder in Outlook. What am I doing wrong?
Cheers
Related
I am having trouble in sending email with both Plain-text & Html content.
In Outlook 2007 the plain-text message is never displayed.
And in Gmail email client by default plain-text is displaying. I need the HTML message to be displayed as default in both Outlook & Gmail, but user can change to plain-text if such settings are made on that system.
I am using following C# code to send emails:
private void SendEmail(string server, string from, string userName, string password, int port , string recipients)
{
MailMessage message = new MailMessage(from,recipients);
message.Subject = "This email message has multiple views.";
message.From = new MailAddress(from);
message.To.Add(recipients);
message.IsBodyHtml = false;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("<html><head></head><body><h1>This is some HTML text2</h1></body></html>", null, MediaTypeNames.Text.Html));
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("This is some plain text2", null, MediaTypeNames.Text.Plain));
SmtpClient client = new SmtpClient(server);
client.Port = port;
NetworkCredential SMTPUserInfo = new NetworkCredential(userName, password);
client.UseDefaultCredentials = false;
client.Credentials = SMTPUserInfo;
client.Send(message);
}
The problem with this code is that (I am not sure), that in Outlook 2007 the email content is displayed initially like below image (default rendering HTML body as plain text):
When I right click & choose "Display as HTML", then the email content is displays like following image (rendering HTML body):
And when I use gmail.com to see the email then email content is displayed like following image (default rendering plain text):
EDIT 1: As suggested I have made changes to my code, now I can see the HTML Email content in Gmail. But in Outlook 2007 after setting plain-text as default view I see the HTML tags as string and it does not show Plain Text which i have drafted which is slightly different from html. Also how do i test the plain text email in Gmail as now in gmail i am receiving only HTML View and i didnt find any way to see plain text view though i have clicked on view original and changed view=om to view=dom in the URL as i have read it on google somewhere.
private void SendEmail(string server, string from, string userName, string password, int port , string recipients)
{
MailMessage message = new MailMessage(from,recipients);
message.Subject = "This email message has multiple views.";
message.From = new MailAddress(from);
message.To.Add(recipients);
message.Body = "This is some plain text2";
message.IsBodyHtml = true;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("<html><head></head><body><h1>This is some HTML text2</h1></body></html>", null, MediaTypeNames.Text.Html));
//message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("This is some plain text2", null, MediaTypeNames.Text.Plain));
SmtpClient client = new SmtpClient(server);
client.Port = port;
NetworkCredential SMTPUserInfo = new NetworkCredential(userName, password);
client.UseDefaultCredentials = false;
client.Credentials = SMTPUserInfo;
client.Send(message);
}
I would try adding the html view after the plain text view.
Also, I usually set the IsBodyHtml flag to true, even when I've got both views defined.
You should set MailMessage.Body to the clear text. Then add the html text as you do via AlternateViews.
At least this is how I have always sent emails with both text and html.
The email client should automatically choose html if it's capable of showing that. It shouldn't display the 'Alternate view' as it does now.
Edit:
I would not set 'IsBodyHtml' to true, it might confuse the mail program, since it's plain text.
Also I would set Encoding to Encoding.UTF8, but I doubt that would solve this problem.
Edit2:
Just checked my mail sender code. I always set a 'message id' header, don't know if that matters:
mailMessage.Headers.Add("message-id", "<" + DateTime.Now.Ticks + "#example.com>");
I have create function to send an email. This function was work successful on localhost but on server its failed without any exception. I know the problem comes from my Port on IP Address.
The sample body is string body = "<p>Please click here</p>Thank You."
The problem is : between IP Address and Port.
Successful send an email if i remove :.
Do you guys have any ideas?
public void Sent(string sender, string receiver, string subject, string body)
{
using (MailMessage mail = new MailMessage(sender, receiver))
{
using (SmtpClient client = new SmtpClient())
{
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "mail.companyName.com.my";
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
client.Send(mail);
}
}
}
You are doing it right, the code to send the mail is ok (you may want to revise the function name and make the smtp host name configurable, but that is not the point here).
The e-mail delivery fails on a relay, there is no immedieate feedback (no exception) to the client about this kind of failure.
The best bet is the IncreaseScoreWithRedirectToOtherPort property set in Set-HostedContentFilterPolicy in case your mail provider is Office365, or a similar spam filter mechanism in any other mail provider that is encountered down the mail delivery chain.
You can set a reply-to address and hope that the destination server will bounce a delivery failure that gives you more information. Or have the admin of the mail server look up the logs. More information here:
https://serverfault.com/questions/659861/office-365-exchange-online-any-way-to-block-false-url-spam
Try setting the 'mail.Body' to receive a Raw Html message instead of a encoded string, like:
mail.Body = new System.Web.Mvc.HtmlHelper(new System.Web.Mvc.ViewContext(), new System.Web.Mvc.ViewPage()).Raw(body).ToString();
Or put a using System.Web.Mvc at the beginning so it gets shorter and easier to understand:
using System.Web.Mvc
mail.Body = new HtmlHelper(new ViewContext(), new ViewPage()).Raw(body).ToString();
I'm trying to understand how From address is used in System.Net.Mail libraries.
For sake of argument I'm going to use google as an example. Below you will find the code that I am using to send out the e-mail.
var message = new MailMessage();
message.To.Add(new MailAddress("john.doe#gmail.com")); // replace with valid value
message.From = new MailAddress("test#gmail.com"); // replace with valid value
message.Subject = "Testing ASP.NET Email system";
message.Body = "This is my test email";
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "test#gmail.com", // replace with valid value
Password = "abc123" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
}
What I am trying to understand is why do I need to set From address and what is the point of it. When you send an e-mail, should the e-mail credentials you logged in with be the From e-mail? Would this mean I can log in as test#gmail.com but when recepient gets the e-mail it will say john#gmail.com if I put john as the From portion?
How does this works exactly?
From is simply how your email client will display the from-email. As long as it's on the same (sub)domain as the actual mail server, most clients will allow it, otherwise you can get warnings such as this:
The reason you can send specify the from-address is because mail-servers do not necessarily have 'accounts' in the same way we do with hosted providers (gmail, hotmail, etc). The specifier before the # is simply a way for inboxes to be organised. For outgoing mail, it's not required from a technical standpoint, as the actual sender is your mail server, not your inbox.
Public mail servers will most likely prevent you from maliciously spoofing an address (ie, dan#gmail.com will probably have his request rejected if trying to send from rob#gmail.com) but the details about this I'm unsure of.
For example, here's a snippet from an email I received:
Received: from mta.email.auspost.com.au (mta.email.auspost.com.au.
[207.67.38.247]) by mx.google.com with ESMTP id
qg3si8833298pbb.100.2015.11.18.19.17.54
...
Received: by mta.email.auspost.com.au id h9kvm4163hs8 for
<==snip==#gmail.com>; Wed, 18 Nov 2015 21:01:47 -0600 (envelope-from
)
From: "Australia Post" <noreply#email.auspost.com.au>
(gmail example. source:
http://www.groovypost.com/wp-content/uploads/2013/05/image20.png)
I'm just trying to get my hmailserver to send mail from my C# program. The part that's killing me is the SSL part.
I originally got this error: The SMTP server requires a secure connection or the client was not authenticated. The server response was: SMTP authentication is required.
So I added: smtp.EnableSsl = true; and now I get Server does not support secure connections.
Here is my code, this is driving me nuts. Do I have to create my own SSL or is there a way to disable SSL on hmailserver side?
MailMessage mail = new MailMessage("jlnt#ademo.net", "com", "NEW Item", emailBody);
SmtpClient smtp = new SmtpClient("1.1.1.250");
smtp.Port = 25;
NetworkCredential login = new NetworkCredential("ja#test.net", "dg");
smtp.Credentials = login;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
Ahh okay what you have to do is in HMailServer go to advanced- ip ranges. Create a new IP range for example if you 192.168.1.2, you have to make the range 192.168.1.1-192.168.1.3, then at bottom uncheck all the required smtp authentication boxes.
Annoying...
To enable secure connection to send email throught your email provider, you have to change the port number.
MailMessage mail = new MailMessage("jlnt#ademo.net", "com", "NEW Item", emailBody);
SmtpClient smtp = new SmtpClient("1.1.1.250");
//smtp.Port =25;
smtp.Port =587;
NetworkCredential login = new NetworkCredential("ja#test.net", "dg");
smtp.Credentials = login;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
i was having this issue, what i did was used localhost ip and EnableSsl to false
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "127.0.0.1";
smtpClient.Credentials = new NetworkCredential("test#123test.com", "pass123");
smtpClient.EnableSsl = false;
// then your other statements like: from, to, body, to send mail
this guide will help you setup custom NetworkCredentials in HMailServer as used above, hope helps someone.
I have stumbled on this question when trying to configure hMailServer to work to e-mail sending from C#. I have tried the following:
C# SmtpClient - does not work with implicit SSL - see this question and answers
AegisImplicitMail from here - could not make it work with UTF-8 strings (I have diacritics in my strings)
MailKit from here - very powerful and mature, no problems using it
I aimed for the following:
decent security
being able to send e-mails to mainstream e-mail providers (e.g. Google, Yahoo) and reach Inbox
being able to receive e-mails from mainstream e-mail providers
C# code
public void MailKitSend(string senderEmail, string senderName, string subject, string bodyText, string receivers, string receiversCc)
{
// no receivers, no e-mail is sent
if (string.IsNullOrEmpty(receivers))
return;
var msg = new MimeMessage();
msg.From.Add(new MailboxAddress(Encoding.UTF8, senderName, senderEmail));
msg.Subject = subject;
var bb = new BodyBuilder {HtmlBody = bodyText};
msg.Body = bb.ToMessageBody();
IList<string> receiversEmails = receivers.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
foreach (string receiver in receiversEmails)
msg.To.Add(new MailboxAddress(Encoding.UTF8, "", receiver));
if (!string.IsNullOrEmpty(receiversCc))
{
IList<string> receiversEmailsCc = receiversCc.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
foreach (string receiverCc in receiversEmailsCc)
msg.Cc.Add(new MailboxAddress(Encoding.UTF8, "", receiverCc));
}
try
{
var sc = new MailKit.Net.Smtp.SmtpClient();
if (!string.IsNullOrWhiteSpace(SmtpUser) && !string.IsNullOrWhiteSpace(SmtpPassword))
{
sc.Connect(SmtpServer, 465);
sc.Authenticate(SmtpUser, SmtpPassword);
}
sc.Send(msg);
sc.Disconnect(true);
}
catch (Exception exc)
{
string err = $"Error sending e-mail from {senderEmail} ({senderName}) to {receivers}: {exc}";
throw new ApplicationException(err);
}
}
hMailServer configuration
1) Opened ports - 25, 143, 465, 995 are opened to ensure that you can send and receive e-mail
2) TCP/IP ports configuration
SMTP / 0.0.0.0 / port 25 / no security (allow receiving start process)
SMTP / 0.0.0.0 / port 465 / SSL/TLS security (must define a SSL certificate)
POP3 / 0.0.0.0 / port 995 / SSL/TLS security (use the same SSL certificate)
3) pre C# testing
Run Diagnostics from hMailServer Administrator
Use an e-mail client that allows manual configuration of various settings such as ports for each protocol, security. I have used Thunderbird. Include sending of e-mails to external providers and receiving e-mails from them (I have tried with Gmail).
I made no changes in IP ranges and left the implicit ones (My computer and the Internet).
Although it's 7 years passed since the accepted answer was posted - I also upvoted it in the beginning - I want to emphasize that the suggested solution disables the whole authentication process which is unnecessary. The problem is the line with :
smtp.UseDefaultCredentials = false;
Just remove that line and it should work.
I post here the working solution for me (note that I'm not using SSL):
MailMessage mail = new MailMessage("a1#test.com", "foooo#gmail.com");
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("a1#test.com", "test");
client.Port = 25;
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "...IPv4 Address from ipconfig...";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
I've found this small code that sends email to gmail users. I'd like the body of the mail to contain html (for example, decoding a link for it to hold different text than the url it's pointing to).
I am using c# .net 3.5. I've used these classes in my code:
MailMessage
SmtpClient
How can this be done?
Here's a copy of my code:
MailMessage message = new MailMessage("me#gmail.com", WebCommon.UserEmail, "Test", context.Server.HtmlEncode("<html> <body> <a href='www.cnn.com'> test </a> </body> </html> "));
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("him#gmail.com", "myPwd");
message.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = cred;
smtp.Port = 587;
smtp.Send(message);
Thanks!
Something like this should work:
Note that MailMessage refers to System.Net.MailMessage. There is also System.Web.MailMessage, which I have never used and -as far as I know- is obsolete.
MailMessage message = new MailMessage();
// Very basic html. HTML should always be valid, otherwise you go to spam
message.Body = "<html><body><p>test</p></body></html>";
// QuotedPrintable encoding is the default, but will often lead to trouble,
// so you should set something meaningful here. Could also be ASCII or some ISO
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
// No Subject usually goes to spam, too
message.Subject = "Some Subject";
// Note that you can add multiple recipients, bcc, cc rec., etc. Using the
// address-only syntax, i.e. w/o a readable name saves you from some issues
message.To.Add("someone#gmail.com");
// SmtpHost, -Port, -User, -Password must be a valid account you can use to
// send messages. Note that it is very often required that the account you
// use also has the specified sender address associated!
// If you configure the Smtp yourself, you can change that of course
SmtpClient client = new SmtpClient(SmtpHost, SmtpPort) {
Credentials = new NetworkCredential(SmtpUser, SmtpPassword),
EnableSsl = enableSsl;
};
try {
// It might be necessary to enforce a specific sender address, see above
if (!string.IsNullOrEmpty(ForceSenderAddress)) {
message.From = new MailAddress(ForceSenderAddress);
}
client.Send(message);
}
catch (Exception ex) {
return false;
}
For more sophisticated templating solutions that render the Body html rather than hard-codin it, there is, for example, the EMailTemplateService in MvcContrib which you can use as a guideline.
One way to do it is to create an alternate html view of the email:
MailMessage message = new MailMessage();
message.Body = //plain-text version of message
//set up message...
//create html view
string htmlBody = "<html>...</html>";
htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
message.AlternateViews.Add(htmlView);
//send message
smtpClient.Send(message);