send email from MVC 4 ASP.NET app - c#

I am trying to setup simple but complete ASP.NET MVC 4 web app, where I can send email to specific address, I configure the web.config file for SMPT settings and code in controller call, but I am getting error message "The SMTP host was not specified"
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="myEmail#hotmail.co.uk">
<network host="smtp.live.com" port="25" userName="myEmail#hotmail.co.uk" password="myPassword" defaultCredentials="true"/>
</smtp>
</mailSettings>
in controller class
var mailMessage = new MailMessage();
mailMessage.To.Add("yourEmail#hotmail.co.uk");
mailMessage.Subject = "testing 2 ";
mailMessage.Body = "Hello Mr. Aderson";
mailMessage.IsBodyHtml = false;
var smptClient = new SmtpClient { EnableSsl = false };
smptClient.Send(mailMessage);
many thanks

Best Idea to use SMTP mail functionality in .NET + MVC/ASP is this open source codeplex library:
http://higlabo.codeplex.com/
Especially since the default-delivered components in .NET framework does fully support all types of SSL/TSL etc. (implicit/explicit mode as keyword here)
http://higlabo.codeplex.com/

From a quick look you haven't set up the "From" property.
var mailMessage = new MailMessage();
mailMessage.To.Add("yourEmail#hotmail.co.uk");
mailMessage.From = new MailAddress("myEmail#hotmail.co.uk");
mailMessage.Subject = "testing 2 ";
mailMessage.Body = "Hello Mr. Aderson";
mailMessage.IsBodyHtml = false;

Your code and configuration look correct.
Are you sure you have put the system.net/mailSettings element in the web.config in the root directory of your web site?
A common mistake is to put such settings in the web.config in the Views folder.
Incidentally, the MailMessage class implements IDisposable, as does the SmtpClient class from .NET 4. So you should be enclosing both in using blocks.

Not sure if smtp.live.com is still valid http://windows.microsoft.com/en-ca/windows/outlook/send-receive-from-app does not seem to list it
I would check if Port 25 is Blocked if Port 25 is blocked, try Port 587 (Might have to enable SSL for 587)

you missing smptClient.Send(mailMessage); at the end of your code
var mailMessage = new MailMessage();
mailMessage.To.Add("yourEmail#hotmail.co.uk");
mailMessage.From = new MailAddress("myEmail#hotmail.co.uk");
mailMessage.Subject = "testing 2 ";
mailMessage.Body = "Hello Mr. Aderson";
mailMessage.IsBodyHtml = false;
//this what you miss
smptClient.Send(mailMessage);
//

do some thing like this
SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtp], Convert.ToInt32(ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtpport]));
if (ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtpUseCredentials] == "true")
{
smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtpusername], ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtppassword], ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtp]);
}
else
{
smtp.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
if (SendTo.Count == 0)
{
SendTo.Add(ConfigurationManager.AppSettings[EFloOnline.Model.Constants.ToMail]);
}
foreach (string recipientemail in SendTo)
{
oEmail.To.Add(recipientemail);
try
{
smtp.Send(oEmail);
}
catch (Exception)
{
}
oEmail.To.Clear();
}
}

I wrote a blog post about doing this.
http://www.bgsoftfactory.net/5-steps-to-send-email-with-mvcmailer-from-an-mvc-4-0-application/
I took the easier way, using MVCMailer. Even if sending email from MVC is quite easy, it's a little more complicated to make it nice, while MVCMailer allow to use razor templates to format the body of your email.
You may save yourself some time by using MVCMailer.

Related

Sending mail from gmail SMTP C# Connection Timeout

I have been trying to send an email via C# from a gmail account for account registration for my website.
I have tried several ways however the same exception continues to pop up: System.Net.Mail.Smtp Exception - Connection has timed out.
This is what I inluded in my Web.config file:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network"
from="Writely <mrbk.writely#gmail.com>">
<network host="smtp.gmail.com"
port="465"
enableSsl="true"
defaultCredentials="false"
userName="mrbk.writely#gmail.com"
password="******" />
</smtp>
</mailSettings>
</system.net>
where writely is the name of my website, and mrbk.writely#gmail.com is the account I wish to send an email from.
Then in my Account Controller when I connect with my database and save the user in my table, I am creating my MailMessage object and attempting to same the mail by:
using (DBConnection conn = new DBConnection())
{
conn.UserInfoes.Add(userInfo);
conn.SaveChanges();
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mrbk.writely#gmail.com");
mail.To.Add("bernice.zerafa11#gmail.com");
mail.Subject = "Welcome to Writely";
mail.Body = "Test content";
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
}
Am I missing something or doing something wrong? I read that this is the good way to do this in some other question on stack overflow so I really don't know what's the problem here.
Thanks for your help :)
You need to tell the SmtpClient what settings to use. It does not automatically read this information from the Web.Config file.
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 465);
smtp.Credentials = new NetworkCredential("mrbk.writely#gmail.com", "***");
smtp.EnableSsl = true;
smtp.Send(mail);
gmail requires authentication:
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for TLS/STARTTLS: 587
Port for SSL: 465
so what i did is
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("mrbk.writely#gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("bernice.zerafa11#gmail.com", "bernice.zerafa11#gmail.com", "Welcome to Writely", "Test content");
I had the exact same problem and it's resolved after switching the port number from 465 to 587.
I had the problem on "email confirmation", "password recovery", and "sending email" and now all 3 problems are resolved :).
I know it's a pretty old post, but I usually use the existing posts to find answers instead of asking for new questions.
Thank you all for all your helps.
As I have already answered here.
This problem can also be caused by a security configuration in you gmail account.
The correct port is 587, but to authenticate you need to allow access from less secure apps in your gmail account.
Try it here
It worked for me, hope it helps..
Example in asp.net web forms/sharepoint
StringBuilder Body = new StringBuilder();
Body.Append("Your text");
String FromEmail = "you email";
String DisplayNameFromEmailMedico = "display when you receive email";
MailMessage message = new MailMessage();
message.From = new MailAddress(FromEmail, DisplayNameFromEmailMedico);
message.To.Add(new MailAddress("myclient#gmail.com"));
message.Subject = "subject that print in email";
message.IsBodyHtml = true;
message.Body = Body.ToString();
SmtpClient client = new SmtpClient();
NetworkCredential myCreds = new NetworkCredential("yoursmtpemail#gmail.com", "key from email smtp", "");
client.EnableSsl = true;
client.Credentials = myCreds;
client.Send(message);

Sending emails using .Net [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending email in .NET through Gmail
I don't know what is the apis needed to send emails using gmail and hotmail using .Net , if someone know it will be very useful for me also how to install those libraries into VS 2010
To send emails, use VS 2010 SMTP. You define related parameters in the .config as follows:
<system.net>
<mailSettings>
<smtp from="youremail#yourdomain.com">
<network host="mail.yourdomain.com" port="yourport" userName="youremail#yourdomain.com" password="yourpassword" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.net>
As an example of the C# code to send emails:
public static void Send(string Subject, string From, string Body, List<emailAddress> CC, MailAddress To, bool BodyHTML)
{
try
{
MailMessage mail = new MailMessage();
if (CC != null)
{
foreach (emailAddress ea in CC)
{
mail.CC.Add(new MailAddress(ea.email, ea.fullname));
}
}
mail.Subject = Subject;
mail.Body = Body;
mail.IsBodyHtml = BodyHTML;
mail.From = new MailAddress(From);
mail.To.Add(To);
SmtpClient client = new SmtpClient();
client.Host = "mail.yourdomain.com";
client.Send(mail);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
You're looking for the System.Net.Mail namespace. No external libraries needed - to start just add a using directive to it at the top of your class.
Here's a site with some good references to get you started:
http://www.systemnetmail.com/

Contact Form; ASP.NET, C#

This should be simple, but there is something I'm not getting. The user fills out info and the btnClick does the code.
I would think the msgToAdd would be who the e-mail is going to. (Testing as my email.)
And that the msgFromAdd would be who the message is from, which is input by the person browsing. (Testing as my wife's email.)
Then the credentials I put in my email/password. (Which in reality, anything "mine" would be x company. So I would need to code in the company email password? :-/)
Anyway, I successfully send email to my address, but it says it's coming from my address and I need it to come from whatever address the user input.
I've searched everywhere, but all the code is the same and it makes no sense to me. Thanks.
SmtpClient smtpClient = new SmtpClient();
MailMessage mailMsg = new MailMessage();
MailAddress msgToAdd = new MailAddress("myemail#gmail.com");
MailAddress msgFromAdd = new MailAddress(tbxEmailAdd.Text);
mailMsg.To.Add(msgToAdd);
mailMsg.From = msgFromAdd;
mailMsg.Subject = ddlEmail.SelectedValue;
mailMsg.IsBodyHtml = true;
mailMsg.Body = tbxEmail.Text;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
smtp.EnableSsl = true;
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Send(mailMsg);
So even with the overkill below, it still doesn't show the real sender's address.
MailAddress msgFromAdd = new MailAddress(tbxEmailAdd.Text);
mailMsg.From = msgFromAdd;
mailMsg.ReplyToList.Add(msgFromAdd);
mailMsg.ReplyTo = msgFromAdd;
mailMsg.Sender = msgFromAdd;
Also, the following DOES make the name show up. Still no email address though!
MailAddress msgFromAdd = new MailAddress(tbxEmailAdd.Text, "NAME");
I'm seriously losing it.
Sounds like google don't let you mess with the "from" header? You might want to try using the "Sender" property, doesn't always render nice in all email clients tho.
MailMessage, difference between Sender and From properties
I would check your web.config (if you have one). There may be a setting like:
<system.net>
<mailSettings>
<smtp from="your address here">
<network host="localhost" password="" userName=""/>
</smtp>
</mailSettings>
</system.net>
that could be overriding your settings.
you're sending email with your smtp credential, so the "from" should be your email. the "From" property in MailMessage is just an optional choise in case you're using an open smtp that needn't credentials.

Troubleshooting "Mailbox unavailable. The server response was: Access denied - Invalid HELO name" when sending email with SmtpClient

I have been trying to send an email by C#. I have Googled for various examples and have taken bits and pieces from each and from the standard code which everyone would most probably be using.
string to = "receiver#domain.com";
string from = "sender#domain.com";
string subject = "Hello World!";
string body = "Hello Body!";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient("smtp.domain.com");
client.Credentials = new NetworkCredential("test#domain.com", "password");
client.Send(message);
However, I keep getting an error stating
System.Net.Mail.SmtpException: Mailbox
unavailable. The server response was:
Access denied - Invalid HELO name (See
RFC2821 4.1.1.1)
So, what do I do now? Is SmtpClient supposed to be special and only work on specific SMTP servers?
It seems your username/password pair is not authenticating successfully with your SMTP server.
EDIT
I think, I found what's wrong here. I have corrected your version below.
string to = "receiver#domain.com";
//It seems, your mail server demands to use the same email-id in SENDER as with which you're authenticating.
//string from = "sender#domain.com";
string from = "test#domain.com";
string subject = "Hello World!";
string body = "Hello Body!";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient("smtp.domain.com");
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("test#domain.com", "password");
client.Send(message);
Have you tried setting your auth credentials in the web.Config?
<system.net>
<mailSettings>
<smtp from="test#foo.com">
<network host="smtpserver1" port="25" userName="username" password="secret" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
and your code behind
MailMessage message = new MailMessage();
message.From = new MailAddress("sender#foo.bar.com");
message.To.Add(new MailAddress("recipient1#foo.bar.com"));
message.To.Add(new MailAddress("recipient2#foo.bar.com"));
message.To.Add(new MailAddress("recipient3#foo.bar.com"));
message.CC.Add(new MailAddress("carboncopy#foo.bar.com"));
message.Subject = "This is my subject";
message.Body = "This is the content";
SmtpClient client = new SmtpClient();
client.Send(message);
Try this:
string to = "receiver#domain.com";
string from = "sender#domain.com";
string subject = "Hello World!";
string body = "Hello Body!";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient("smtp.domain.com");
// explicitly declare that you will be providing the credentials:
client.UseDefaultCredentials = false;
// drop the #domain stuff from your user name: (The API already knows the domain
// from the construction of the SmtpClient instance
client.Credentials = new NetworkCredential("test", "password");
client.Send(message);
In my case, it was a wrong port. The configuration provided by the hosting didn't worked both SSL (465) and no SSL (25).
I used MS Outlook to "crack" the configuration, and then copied to my application. It was 587 SSL.
This can happen if you don't set EnableSsl.
client.EnableSsl = true;
If you have a webmail client available and you see a cPanel logo it could be a setting there as well.
We got the exception and asked our hosting company to go into:
"Root WHM > Service Configuration >
Exim Configuration Manager > Basic Editor > ACL Options"
and set the Require RFC-compliant HELO setting to Off.
This worked for us after fixing the next error:
SMTP AUTH is required for message submission on port 587
Source:
https://serverfault.com/a/912351/293367

Send mail in asp.net

I am using asp.net 3.5 and C#.
I want to send mail from asp.net, for that I have got some details from my hosting provider
which are these:
mail.MySite.net
UserName
Password
But I am unable to send mail through these details, I have done the following changes in my web.config file:
<system.net>
<mailSettings>
<smtp>
<network
host="mail.MySite.net"
port="8080"
userName="UserName"
password="Password" />
</smtp>
</mailSettings>
</system.net>
Also, at the code behind I am writing this function:
MailMessage mail = new MailMessage("webmaster#mySite.net", "XYZ#gmail.com");
mail.Subject = "Hi";
mail.Body = "Test Mail from ASP.NET";
mail.IsBodyHtml = false;
SmtpClient smp = new SmtpClient();
smp.Send(mail);
but I am getting error message as message sending failed.
Please let me know what I am doing wrong and what I have to do to make it work fine.
Thanks in advance.
Do you need to provide the client credentials?
smp.Credentials = CredentialCache.DefaultNetworkCredentials;
or
smp.Credentials = new NetworkCredential("yourUserID", "yourPassword", "yourDomainName");
Also, the exact exception you are getting would be useful.
See a post by Scott Guthrie for more help.
I doubt port 8080 is the correct smtp port. Perhaps port 25 or 587.
Sending an email through asp.net c# is not a complicated thing... just we know about smtp port and host...
MailAddress to = new MailAddress("Email Id");
MailAddress from = new MailAddress("Email Id");
MailMessage mail = new MailMessage(from, to);
mail.Subject = "";
mail.Body = "";
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new NetworkCredential(
"Email Id", "Password");
smtp.EnableSsl = true;
smtp.Send(mail);
Without using SMTP,Add using Microsoft.Office.Interop.Outlook; reference
Application app = new Application();
NameSpace ns = app.GetNamespace("mapi");
ns.Logon("Email-Id", "Password", false, true);
MailItem message = (MailItem)app.CreateItem(OlItemType.olMailItem);
message.To = "To-Email_ID";
message.Subject = "A simple test message";
message.Body = "This is a test. It should work";
message.Attachments.Add(#"File_Path", Type.Missing, Type.Missing, Type.Missing);
message.Send();
ns.Logoff();
I have very similar code to yours that works, I think the difference is you need to supply the IP address to your SMTP server in the constructor for the SMTP client.
MailMessage Email = new MailMessage("donotreply#test.com", "receiver#test.com");
Email.Subject = "RE: Hello World.";
Email.Body = "Hello World";
Email.IsBodyHtml = false;
SmtpClient Client = new SmtpClient(SMTP_SERVER); //This will be an IP address
Client.Send(Email);
Hope that helps! :)
(Btw, I've used this in Winforms, windows services, and ASP .NET. In ASP .NET I didn't need to supply anything in the aspx page.)

Categories