Error in sending email on live server - c#

I am sending email using c#:
protected void SendEmailToVisitor(string Name, string Email, string Contact, string Message, string Subject)
{
string myEmail = ConfigurationManager.AppSettings["Email"];
MailMessage objMail = new MailMessage();
objMail.From = new MailAddress(myEmail);
objMail.Subject = "Chanderraj.com";
objMail.To.Add(Email);
objMail.IsBodyHtml = true;
StringBuilder emailMessage = new StringBuilder();
emailMessage.Append("<h2>Hi, "+Name+",</h2> <br/>");
emailMessage.Append("Thank you for writing us. <br/><br/><br/>");
emailMessage.Append("Best wishes from http://www.chanderraj.com");
objMail.Body = emailMessage.ToString();
SmtpClient objSmtpClient = new SmtpClient();
objSmtpClient.UseDefaultCredentials = false;
// objSmtpClient.EnableSsl = true;
objSmtpClient.Send(objMail);
this.Reset();
lblSent.Text = Name + ", your message sent.";
}
<system.net>
<mailSettings >
<smtp>
<network host="smtp.gmail.com" userName="chanderraj1989#gmail.com" enableSsl="true" password="xxxxxxxxxx" port="587" />
</smtp>
</mailSettings>
If i add enableSsl in config it shows configuration error before page loads:
Unrecognized attribute 'enableSsl'.
may be this is due to older version of .NET on server.
So, i removed enablSsl from config and put it in code then it shows:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

Yes, it is true that for .NET 3 and earlier you can not use enableSSL property in config file.
For your problem you can add line,
SmtpClient objSmtpClient = new SmtpClient();
objSmtpClient.EnableSsl = true; // Add this line of code. Hope this works
Also add this line in your config file,
<smtp deliveryMethod="Network" from="test#gmail.com">
For .NET 4: yes, You can use add the enableSSL tag in config section.

Not absolute solution but it worked.
As i have a domain chanderraj.com and a domain has option of creating emails like info#chanderraj.com. So i have created one and specified in my config file in place of Gmail id and password(shown in question).

Related

why email is not sending here?

I have a code for sending emails:
public static bool SendEmail(
string fromEmail, string toEmail,
string subject, string body,
bool isBodyHtml = false, bool isThrowException = false)
{
var message = new MailMessage(fromEmail, toEmail)
{
IsBodyHtml = isBodyHtml,
Subject = subject,
Body = body,
};
using (var client = new SmtpClient())
{
try
{
client.Send(message);
}
catch (Exception ex)
{
if (isThrowException)
{
throw new Exception(ex.ToString());
}
}
}
return true;
}
In web.config I have:
<system.net>
<mailSettings>
<smtp>
<network host="smtp.bizmail.yahoo.com" port="25" enableSsl="true" userName=helpdesk#global.com" password="#cr123" defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
Now I don't have any exception, still mail is not receiving at the other end.
I am able to login to yahoo.com by my credentials.
still
client->credentils->domain=""
client->ServicePoint = 'client.ServicePoint' threw an exception of type 'System.TypeInitializationException'
What's gone wrong with it?
The code was working well... before 1 month, I didn't change a single line, what's gone wrong?
Add connection properties and credentials to your code:
NetworkCredentials Credencials = new NetworkCredential(SmtpUsername, SmtpPassword);
client.Host = SmtpHost;
client.Port = SmtpPort;
client.Credentials = Credencials;
First up all thanks to all who tried to help you.
As in the Question i mentioned there is an error while creating a new object of smtp.
smtp will read the web.config and create an object with respect to web.config.
So i came to know that the problem is with web.config .I was also sure that there is nothing wrong with the C# code. so i analysed the web.config and found some filter.
<filter level="TraceEventType.Error" />
basically i used this for removing error message for azure version.
which is causing problem for Serverpoint while creating an object of smtp.
So I just removed the line. and it worked fine.
I got to know not only smtp tag, other tags in web.config file will also effect the current problem.

System.Net mail settings using Network Solutions hosted email

I am trying to use my email service through Network Solutions (NetSol) so that emails sent via the application come from our domains service#ourdomain address.
I cannot seem to make it work, and I am not sure it is even doable since its a webmail service which I can access in a browser using a url like http://mail.ourdomain.com.
According to their site, the smtp settings can be found here
NetSol smtp
Using that information I set up my mail settings as follows
<mailSettings>
<smtp deliveryMethod="Network">
<network host="smtp.ourdomain.com" port="587" userName="service#ourdomain.com" password="xxxxxxxx" enableSsl="true" />
</smtp>
</mailSettings>
I know the password is correct as I'm able to login to my mail in the webbrowser so I don't believe its a credentials error although the error in the method is erring on the credential piece.
private async Task SendMailMessageAsync(MailMessage msg)
{
var acct = Username;
var pwd = Password;
msg.IsBodyHtml = true;
using (var mailClient = new SmtpClient())
{
if (acct != string.Empty && pwd != string.Empty)
{
var credentials = new NetworkCredential(acct, pwd);
mailClient.Credentials = credentials; //ERRING HERE
}
await mailClient.SendMailAsync(msg);
}
}
Is anyone familiar with the proper setup for NetSol professional email?
UPDATE:
For some reason, my code edit in the answer I accepted wasn't accepted. So here is the code, in working order based on the comments in the accepted answer.
public void SendNetSolEmail()
{
var sender = "whatever#yourdomain.com";
var pass = "yourpassword";
var mailMessage = new MailMessage(sender, "sendto_emailaddress", "Hi there", "This method works fine!");
var mailClient = new SmtpClient("mail.yourdomain.com", 587)
{
Credentials = new NetworkCredential(sender,pass),
EnableSsl = false, //important for Network Solutions mail
DeliveryMethod = SmtpDeliveryMethod.Network
};
mailClient.Send(mailMessage);
}
A simple working example of connecting to NetSol's smtp
System.Net.Mail.SmtpClient mailMsg = new System.Net.Mail.SmtpClient("mail.domain.com", 587);
mailMsg.Credentials = new System.Net.NetworkCredential("username#domain.com", "password");
mailMsg.SendMailAsync("username#domain.com", "someone.somewhere#somedomain.com", "Hi Someone", "Body of the email");
and the last note as I see you have ssl enabled; Here it is direct from NetSol:
Note - Make sure you are not chosing and SSL type, this option should be turned off, or "None" should be selected.

Configuring web.config to send emails?

I'm about to deploy my first ASP.NET website to Azure:
There is a contact form in my website with 4 text boxes (email, name, subject and body) and send button. I use this configuration to send emails:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="Mohamed <name#outlook.com>">
<network host="Smtp.live.com" port="587" enableSsl="true" userName="name#outlook.com" password="mypassword"/>
</smtp>
</mailSettings>
</system.net>
And this is the handler for the send button
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string fileName = Server.MapPath("~/App_Data/Message.txt");
string mailBody = File.ReadAllText(fileName);
mailBody = mailBody.Replace("##Name##", TextBoxName.Text);
mailBody = mailBody.Replace("##Email##", TextBoxEmail.Text);
mailBody = mailBody.Replace("##Subject##", TextBoxSubject.Text);
mailBody = mailBody.Replace("##Body##", TextBoxBody.Text);
MailMessage visitorMessage = new MailMessage();
visitorMessage.Subject = "New Message: " + TextBoxSubject.Text;
visitorMessage.Body = mailBody;
visitorMessage.From = new MailAddress(TextBoxEmail.Text, TextBoxName.Text);
visitorMessage.To.Add(new MailAddress("name#outlook.com", "Mohamed"));
visitorMessage.ReplyToList.Add(new MailAddress(TextBoxEmail.Text));
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(visitorMessage);
LabelIRespond.Visible = true;
}
}
I use these settings for the IIS server, obviously it's not working with production server.
Please tell me what changes should I make to enable this function?
EDIT
when I send message from the form, The process terminates, and I receive a privacy warning to my email.
Here is a blog post on sending emails using windows azure:
http://blog.smarx.com/posts/emailtheinternet-com-sending-and-receiving-email-in-windows-azure
TLDR - don't use your personal email on a cloud host to send emails, it's likely these services black list cloud host IP address ranges to help prevent spam. Get a legit SMTP server set up either on prem, in the cloud, or use a third party service as pointed out in the post linked.

Can we send mails from localhost using asp.net and c#?

i am using using System.Net.Mail;
and following code to send mail
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
// Set the sender's address
message.From = new MailAddress("fromAddress");
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
// Allow multiple "Cc" addresses to be separated by a semi-colon
if (ccAddress.Trim().Length > 0)
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
// Set the subject and message body text
message.Subject = subject;
message.Body = messageBody;
// Set the SMTP server to be used to send the message
client.Host = "YourMailServer";
// Send the e-mail message
client.Send(message);
for Host i am providing client.Host = "localhost";
for this its falling with error
No connection could be made because the target machine actively
refused it some_ip_address_here
and when i use client.Host = "smtp.gmail.com";
i get following error
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
i am not able to send mail through localhost.
Please help me out, i am new to c# please correct me in code where i am going wrong..?
Here is some code that works for sending mail via gmail (code from somewhere here on stackoverflow. It is similar to the code here: Gmail: How to send an email programmatically):
using (var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("yourmail#gmail.com", "yourpassword"),
EnableSsl = true
})
{
client.Send("frommail#gmail.com", "tomail#gmail.com", "subject", message);
}
For sending mail from client.Host = "localhost" you need set up local SMTP server.
For sending mail via Google (or via any other SMTP server, including your own local SMTP) you must set username, password, ssl settings - all as required by SMTP server chosen, and you need to read their help for this.
For example Google says that you need SSL, port 465 or 587, server smtp.gmail.com and your username and password.
You can assign all this values in .config file.
<system.net>
<mailSettings>
<smtp>
<network host="smtp.gmail.com" enableSsl="true" port="587" userName="yourname#gmail.com" password="password" />
</smtp>
</mailSettings>
</system.net>
Or set to SmtpClient in code before every use:
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSSL = true;
client.Credentials = new NetworkCredential("yourname#gmail.com", "password");
Place this code inside a <configuration> </configuration> in web.config file
<system.net>
<mailSettings>
<smtp>
<network host="smtp.gmail.com" enableSsl="true" port="587" userName="youremail#gmail.com" password="yourpassword" />
</smtp>
</mailSettings>
</system.net>
then backend code
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress("email#gmail.com");
message.To.Add(new MailAddress(TextBoxEadd.Text));
message.CC.Add(new MailAddress("email#gmail.com"));
message.Subject = "New User Registration ! ";
message.Body = "HELLO";
sr.Close();
SmtpClient client = new SmtpClient();
client.Send(message);
I hope this code help you! :)
use this Line..Dont Use Port And HostName
LocalClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
I just wanted to add that Gmail now requires App Password in order to use it from other applications. Check this link. I had to find it the hard way. After I created an App Password and then I changed the NetworkCredentials to use it to send emails.

Send mail with attachment

Edit: I'm able to send mail without attachment
Getting this error while trying to send mail:
System.Net.Mail.SmtpException: The operation has timed out.
Following is my code:
public static void SendMailMessage(string to, string subject, string body, List<string> attachment)
{
MailMessage mMailMessage = new MailMessage();
// string body; --> Compile time error, body is already defined as an argument
mMailMessage.From = new MailAddress("abc#gmail.com");
mMailMessage.To.Add(new MailAddress(to));
mMailMessage.Subject = subject;
mMailMessage.Body = body;
foreach (string s in attachment)
{
var att = new Attachment(s);
mMailMessage.Attachments.Add(att);
}
// Set the format of the mail message body as HTML
mMailMessage.IsBodyHtml = true;
// Set the priority of the mail message to normal
mMailMessage.Priority = MailPriority.High;
using (SmtpClient mSmtpClient = new SmtpClient())
{
mSmtpClient.Send(mMailMessage);
}
}
Web Config
<system.net>
<mailSettings>
<smtp from="mailid">
<network host="smtp.gmail.com" port="587" enableSsl="true" userName="username" password="pass" />
</smtp>
</mailSettings>
Note : Attachments not exceeding its limit(below than 25 mb)
What can I do to solve this problem, or what am I missing?
So basically we discovered during the chat that the problem occurs
because the upload of the attachments takes to long.
One way to solve it is to increase the timeout value of the SmtpClient:
mSmtpClient.Timeout = int.MaxValue;
Note: Use int.MaxValue for testing but use a more realistic value for the deployed solution.
Setup a local smtp server to relay through, or use something like http://aws.amazon.com/ses/. I don't think google is going to allow you to programtically relay through their servers.

Categories

Resources