Emails not being delivered to Gmail, Yahoo, Hotmail - c#

I am attempting to send emails from a Web App written in C#/ASP.NET.
I am trying to send both HTML and text version of the email.
However, when I attempt to send to a Gmail, Yahoo, Hotmail, AOL, etc. email address it does not show up in their inbox.
When I send strictly text, without the HTML alternate view, it delivers just fine.
Has anyone here had any experience with this?
The email is delivered fine to our Hosted Exchange server "#mxxx.com"
Thanks!
EDIT: One more thing. When the emails don't get delivered, we don't receive any type of failed delivery notification, it essentially disappears.
Code:
// email the user
MailMessage message = new MailMessage("support#mxxx.com", user.EmailAddress);
message.Bcc.Add("xxx#gmail.com");
message.Bcc.Add("xxx#yahoo.com");
message.Bcc.Add("xxx#hotmail.com");
message.Subject = "Your \"mxxx.com\" password has been reset";
message.ReplyToList.Add(new MailAddress("support#mxxx.com"));
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.Delay |
DeliveryNotificationOptions.OnSuccess;
message.Sender = new MailAddress("support#mxxx.com");
string htmlbody = "<html><body><p>Dear " + name + ":</p>" +
"<p>Your password at \"mxxx.com\" has been reset to: " + newPassword + "</p>" +
</body></html>";
var plainTextBody = "test plain text";
AlternateView plainTextView =
AlternateView.CreateAlternateViewFromString(
plainTextBody, message.BodyEncoding, MediaTypeNames.Text.Plain);
plainTextView.TransferEncoding = TransferEncoding.Base64;
message.AlternateViews.Add(plainTextView);
AlternateView htmlview =
AlternateView.CreateAlternateViewFromString(
htmlbody, message.BodyEncoding, MediaTypeNames.Text.Html);
htmlview.TransferEncoding = TransferEncoding.Base64;
message.AlternateViews.Add(htmlview);
SmtpClient mailMan = new SmtpClient();
mailMan.Send(message);

What if you avoid using AlternateView and specify that the body is HTML?
Consider testing the next snippet?:
MailMessage message = new MailMessage("support#mxxx.com", user.EmailAddress);
message.Bcc.Add("xxx#gmail.com");
message.Bcc.Add("xxx#yahoo.com");
message.Bcc.Add("xxx#hotmail.com");
message.Subject = "Your \"mxxx.com\" password has been reset";
message.ReplyToList.Add(new MailAddress("support#mxxx.com"));
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.Delay |
DeliveryNotificationOptions.OnSuccess;
message.Sender = new MailAddress("support#mxxx.com");
string htmlbody = "<html><body><p>Dear " + name + ":</p>" +
"<p>Your password at \"mxxx.com\" has been reset to: " + newPassword + "</p>" +
</body></html>";
message.Body = htmlbody;
message.IsBodyHtml = true;
SmtpClient mailMan = new SmtpClient();
mailMan.Send(message);

Related

Sending User Message From My Site To My Email In ASP.NET Core MVC 2.1 [duplicate]

This question already has an answer here:
Contact Us Page
(1 answer)
Closed 4 years ago.
I have a C# code as below in ASP.NET Core MVC 2.1 to send user message to me from my site:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ContactSohJel(string txtEmail, string txtSubject, string txtFirstName, string txtLastName, string txtMessage)
{
using (MailMessage message = new MailMessage())
{
try
{
MailMessage mail = new MailMessage();
//mail.From = new MailAddress("mail#sohjel.ir");
mail.To.Add("mail#sohjel.ir");
mail.CC.Add("sohjelveh#gmail.com");
mail.Bcc.Add("sohjel#yahoo.com");
mail.From = new MailAddress(txtEmail, txtSubject, System.Text.Encoding.UTF8);
mail.Subject = "Subject: " + txtSubject + " --- " + "This Message Has Been Sent From: SohJel Let's Learn English WebSite. Microsoft ASP.NET Core MVC";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "<h1>Sender</h1><br/><h2>Information:<br/></h2><h3><strong>First Name: </strong>" + txtFirstName + "<br/><strong>Last Name: </strong>" + txtLastName + "<br/><strong>Email: </strong>" + txtEmail + "<br/><strong>Subject: </strong>" + txtSubject + "<br/><h2>Message: <br/></h2><h3><textarea rows=15 cols=80>" + txtMessage + "</textarea><br/>" + "<br/>" + "<br/>" + "<br/>" + "</h3>" + "This Message Has Been Sent From: SohJel Let's Learn English WebSite.";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("mail#sohjel.ir", "********");
client.Port = **;
//client.Port = ***;
client.Host = "***.***.***.**";
client.EnableSsl = false;
await client.SendMailAsync(mail);
TempData["testmsg"] = " Your Message Sent Successfully To Me! ";
}
catch (Exception ex)
{
TempData["testmsg"] = " An Error Occured!: Your Message Was NOT Sent To Me! ";
ViewBag.Title = ex.Message;
}
}
return View("ContactSohJel");
}
Now my problem is message isn't sent to me!
* this code works with my gmail accout on my LOCALHOST but it doesn't work on my website!
The error seems pretty clear. The "FROM" address domain must be the same as the authentication domain.
You are passing in, presumably, the user's email address to use in the FROM header. That's not ok. You should use your own address in the FROM field.

Send a hyperlink within email

I have a variable name that holds a hyperlink; I would like to send the hyperlink within an email.
I can send the email ok, but the hyperlink appears as text i.e.[http://www.google.com]Click here
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"], "FileTransfer");
mailMessage.Subject = "FileTransfer";
var body = new StringBuilder();
body.AppendFormat("<html><head></head><body> Hello World" + "<br />" + "<a href='{0}'>Click here</a></body></html>", link);
mailMessage.IsBodyHtml = true;
mailMessage.Body = body.ToString();
mailMessage.To.Add(new MailAddress(toEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}
Try replacing this...
body.AppendFormat("<html><head></head><body> Hello World" + "<br />" + "<a href='{0}'>Click here</a></body></html>", link);
with this
body.Append("<html><head></head><body> Hello World" + "<br />" + "Click here</body></html>");
According to https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews(v=vs.110).aspx
It seems like you have to set the content type and create an alternate view. Or if you don't want to have a plaintext version, set the default view to text/html
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
recipients,
"This e-mail message has multiple views.",
"This is some plain text.");
// Construct the alternate body as HTML.
string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
body += "</HEAD><BODY><DIV><FONT face=Arial color=#ff0000 size=2>this is some HTML text";
body += "</FONT></DIV></BODY></HTML>";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);
Some email provider software won't be capable of displaying text/html. Whether this is a protective measure or just lack of support, I believe this would be the best solution since it compensates for both cases.

Send Some Form Of Notification When An Asp.net Windows Form Is Submitted

I have anasp.net web form which on click of a button shows a modal with 3 fields and a submit button.
All i want is for some sort of notification to be sent to me with the details of the form.
The thing is, is that my application sits on our 'DEV' environment and i was thinking of an email being sent to my email address in our 'Live' environment so it will need to be done via Microsoft Outlook but i cant figure out how to do this at all.
I have done this in the past using 'Hotmail' but i cant figure out or get the email to be sent to me at all.
I have tried the following
using Microsoft.Office.Interop.Outlook;
protected void BtnSuggestPlace_Click(object sender, EventArgs e)
{
MailMessage message = new MailMessage();
message.From = new MailAddress("antonydev#dev1.test.com");
message.To.Add(new MailAddress("antony#test.co.uk"));
message.Subject = "This is my subject";
message.Body = "This is the content";
SmtpClient client = new SmtpClient();
client.Send(message);
}
and i have also tried the code i use for the hotmail
using System.Net.Mail;
using System.Net;
using System.IO;
protected void BtnSuggestPlace_Click(object sender, EventArgs e)
{
//Creates the email object to be sent
MailMessage msg = new MailMessage();
//Adds your email address to the recipients
msg.To.Add("antony#test.co.uk");
//Configures the address you are sending the email from
MailAddress address = new MailAddress("antonydev#dev1.test.com");
msg.From = address;
//Allows HTML to be used when setting up the email body
msg.IsBodyHtml = true;
//Email subjects title
msg.Subject = "Place Suggestion";
msg.Body = "<b>" + lblPlace.Text + "</b>" + " " + fldPlace.ToString()
+ Environment.NewLine.ToString() +
"<b>" + lblLocation.Text + "</b>" + " " + fldLocation.ToString()
+ Environment.NewLine.ToString() +
"<b>" + lblName.Text + "</b>" + " " + fldName.ToString();
//Configures the SmtpClient to send the mail
**NOT TO SURE IF REQUIRED OR NOT**
SmtpClient client = new SmtpClient("smtp.live.com", 587);
client.EnableSsl = true; //only enable this if the provider requires it
//Setup credentials to login to the sender email address ("UserName", "Password")
**NO IDEA WHAT TO PUT HERE AS PASSWORDS EXPIRE EVERY 28DAYS**
NetworkCredential credentials = new NetworkCredential("antonydev#dev1.testcom", "CurrentPassword");
client.Credentials = credentials;
//Send the email
client.Send(msg);
// Create a Outlook Application and connect to outlook
Application OutlookApplication = new Application();
// create the MailItem which we want to send
MailItem email = (MailItem)OutlookApplication.CreateItem(OlItemType.olMailItem);
// Add a recipient for the email
email.Recipients.Add("antonydev#dev1.test.com");
// add subject and body of the email
email.Subject = "Test";
email.Body = "This is a test email to check outlook email sending code";
//send email
email.Send();
}
all i need is something passes what was entered to me but not sure how or what way to do it
Update
I have decided to setup a new gmail acc and use that but it always drops into my catch i suspect it's timing out can anyone help please.
The InnerException Message is:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 173.194.67.109:587
protected void BtnSuggestPlace_Click(object sender, EventArgs e)
{
#region Email
try
{
//Creates the email object to be sent
MailMessage msg = new MailMessage();
//Adds your email address to the recipients
msg.To.Add("antony#test.co.uk");
//Configures the address you are sending the email from
MailAddress address = new MailAddress("NewGmailEmailAddress#gmail.com");
msg.From = address;
//Allows HTML to be used when setting up the email body
msg.IsBodyHtml = true;
//Email subjects title
msg.Subject = "Place Suggestion";
msg.Body = "<b>" + lblPlace.Text + "</b>" + " " + fldPlace.Text
+ Environment.NewLine.ToString() +
"<b>" + lblLocation.Text + "</b>" + " " + fldLocation.Text
+ Environment.NewLine.ToString() +
"<b>" + lblName.Text + "</b>" + " " + fldName.Text;
SmtpClient client = new SmtpClient("smtp.gmail.com");
NetworkCredential nc = new NetworkCredential("XXXusername", "MyPassword");//username doesn't include #gmail.com
client.UseDefaultCredentials = false;
client.Credentials = nc;
client.EnableSsl = true;
client.Port = 587;
//Send the email
client.Send(msg);
}
catch
{
//Lets the user know if the email has failed
lblNotSent.Text = "<div class=\"row\">" + "<div class=\"col-sm-12\">" + "There was a problem sending your suggestion. Please try again." + "</div>" + "</div>" + "<div class=\"form-group\">" + "<div class=\"col-sm-12\">" + "If the error persists, please contact Antony." + "</div>" + "</div>";
}
#endregion
}
Here is some code I use to send SMTP mail using a gmail account:
public static void Send(string subject, string message, params string[] recipients)
{
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com");
System.Net.NetworkCredential nc = new System.Net.NetworkCredential([YourAccountName], [YourAccountPassword]);//username doesn't include #gmail.com
client.UseDefaultCredentials = false;
client.Credentials = nc;
client.EnableSsl = true;
client.Port = 587;
try
{
string recipientString = string.Join(",", recipients);
client.SendAsync([YourAccountName] + "#gmail.com", recipientString, subject, message, null);
}
catch (Exception ex)
{
Logger.Report(ex);
}
}
173.194.67.109 is a valid gmail IP: don't specify port in order to estabilish an smtp connection with SSL (587 is the TLS port).
I also recommend using web.config to store smtp settings:
<appSettings>
<add key="enableSSL" value="true"/>
</appSettings>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="yourgmail#gmail.com">
<network
host="smtp.gmail.com"
userName="yourgmail#gmail.com"
password="YourPassword" />
</smtp>
</mailSettings>
</system.net>
So your code could be something like this:
Dim email As New System.Net.Mail.MailMessage()
email.Body = "YourBody"
email.Subject = "YourSubject"
email.To.Add("yourrecipient#email.com")
Dim smtp As New System.Net.Mail.SmtpClient()
smtp.EnableSsl = System.Configuration.ConfigurationManager.AppSettings("enableSSL")
smtp.Send(email)
It turns out that the firewall is blocking it so the issue is not with the code itself.

Contact form doesn't work

I have a problem with a form, I can't send it. If I put wrong details (secure code, email, empty fields etc.), I get errors on screen, which is correct.
But when I enter all correct data, I can't send the form, I get this error:
There was an error submitting your form. Please check the following:
But the list is empty.
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress("noreply#domain.com", "string1");
// decide who message goes to
string emailGoesTo = "person1#domain.com";
MailAddress toAddress = new MailAddress(emailGoesTo.ToString(), "string1");
message.From = fromAddress;
message.To.Add(toAddress);
message.To.Add("person2#domain.com");
message.Subject = "string2";
message.Body = "New Website Contact Request";
message.Body += "------------------------------------------\r\n";
message.Body += "Name: " + your_name.Text + "\r\n";
message.Body += "Email: " + your_email.Text + "\r\n";
message.Body += "Telephone: " + your_telephone.Text + "\r\n";
message.Body += "Company: " + your_company.Text + "\r\n";
message.Body += "Address: " + your_address.Text + "\r\n";
message.Body += "Postcode: " + your_zip.Text + "\r\n";
message.Body += "Enquiry: " + your_enquiry.Text + "\r\n";
// smtpClient.Host = "string3";
smtpClient.Host = "string4";
smtpClient.Credentials = new System.Net.NetworkCredential("string5", "string6");
smtpClient.Send(message);
Response.Redirect("thankyou.aspx");
}
catch (Exception ex)
{
statusLabel.Text = "Coudn't send the message!";
}
I'm noobie, so is there any1 string5 & string6 please?
Also what is wrong? How to make this form working?
never tried to use smtpclient.host but the below works. Just need to add in the ip/host name of the mail server and make sure it is set up to allow relay from the machine calling the code. and replace the strings with the text you want. I'd suggest starting with something simple rather than feeding from form fields to eliminate any outside issues. Once the mail is sending then start adding additional pieces in.
public static string mailServer = 'IP address or host name of mail server'
public static void Send()
{
string subject = "test subject";
string address = "test#somedomain.com";
string body = "some mail body";
MailMessage mm = new MailMessage();
mm.From = new MailAddress("no-reply#domain.net"); //on behalf of
mm.To.Add(new MailAddress(address));
mm.IsBodyHtml = true;
mm.Subject = subject;
mm.Body = body;
SmtpClient server = new SmtpClient(mailServer);
server.Send(mm);
}
}
string5 and string6 is email credentials on mail server (username and password). You should know it better us ;-)
You need to update your smtpClinet.Host with the name / domain information for your mail server. The Credentials need to be updated with the username and password of a user that can access your mail server. Sometimes this can be left out.

Show Progress bar with smtpClient.send

I am using this function to send mails via gmail.
private bool uploadToGmail(string username, string password , string file ,
string backupnumber)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("jain#gmail.com");
mail.To.Add("jain#gmail.com");
mail.Subject = "Backup mail- Dated- " + DateTime.Now + " part - " +
backupnumber;
mail.Body = "Hi self. This mail contains \n backup number- " +
backupnumber + " \n Dated- " + DateTime.Now ;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(file);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials =
new System.Net.NetworkCredential("jain#gmail.com", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Timeout = 999999999;
SmtpServer.Send(mail);
// MessageBox.Show("mail Sent");
return true;
}
Now I want to show a progress bar (in case there is a large attachment) to show the upload . Is this possible ? I think I know how to use a progress bar, but don't know how to use it with Smtpclient.send() .
any help ?
Thanks
You should use SendAsync and subscribe to SendCompleted, to know, when the sending your mail completed. There is no way to get the progress of the send process, though...

Categories