Sending Email through .NET code - c#

I'm unable to send an email to yahoo server as my code is throwing exception as 'Failure Sending mail' in C# 2008.
Please provide SMTP HostName, PortName for yahoo server and gmail server.
And also kindly provide a good working C# code with which i can send an email directly to any of the mail servers.
Please provide complete working code...so that i will copy into Visual studio environment and execute the same.
As i'm getting exception since morning....unable to resolve the issue.
Kindly help me in this regard.

For Gmail:
var client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Credentials = new NetworkCredential("youraccount#gmail.com", "secret");
var mail = new MailMessage();
mail.From = new MailAddress("youraccount#gmail.com");
mail.To.Add("youraccount#gmail.com");
mail.Subject = "Test mail";
mail.Body = "test body";
client.Send(mail);
For Yahoo:
var client = new SmtpClient("smtp.mail.yahoo.com", 587);
client.Credentials = new NetworkCredential("youraccount#yahoo.com", "secret");
var mail = new MailMessage();
mail.From = new MailAddress("youraccount#yahoo.com");
mail.To.Add("destaccount#gmail.com");
mail.Subject = "Test mail";
mail.Body = "test body";
client.Send(mail);

Bear in mind that some ISPs (including mine) force their clients to use their SMTP server (as a relay). Spamming protection is the reason.
So you should avoid sending e-mail to the Internet from a client application, unless you give user a chance to specify his SMTP hostname or your app relies on the user's e-mail software (MAPI,...).

Imagine how much easier it would be for us to help you, if you posted the complete exception message, along with a stack trace.
Also, go one step farther and enable logging for System.Net.Mail, so we can see any possible failures at the network level.
If you don't know how to enable logging for SNM, here is a link:
http://systemnetmail.com/faq/4.10.aspx
Thanks!
Dave

There are two ways in which We can send the mail,
1)First is using javascript link "mailTo".This will not send the mail automatically but it will just open the mail window.Refer to the below code
<a class="label" onclick='javascript:buildEmail(this)'>Send Mail</a>
Find below the js method
function buildEmail(el) {
var emailId = Usermail#gmail.com;
var subject="Hi";
var body="Hello";
el.href = "mailto:" + emailId + "?Subject=" + escape(subject) +
"&Body=" + escape(body);
}
2)The second way is to use System.Net.Mail which will automatically send the mail to the recipients in the secured manner.
string subject="Hello";
string body="Data";
using ( MailMessage objMail = new MailMessage ( "Yourmail#gmail.com", "Usermail#gmail.com" ) )//From and To address respectively
{
objMail.IsBodyHtml = false;// Message format is plain text
objMail.Priority = MailPriority.High;// Mail Priority = High
objMail.Body = "Hello";
ArrayList CCarr = new ArrayList();//Assume we add recipients here
// populate additional recipients if specified
if ( ( CCarr != null ) && ( CCarr .Count > 0 ) )
{
foreach ( string recipient in CCarr )
{
if ( recipient != "Please update the email address" )
{
objMail.CC.Add ( new MailAddress ( recipient ) );
}
}
}
// Set the subject of the message - and make sure it is CIS Compliant
if ( !subject.StartsWith ( "SigabaSecure:" ) )
{
subject = "SigabaSecure: " + subject;
}
objMail.Subject = subject;
// setup credentials for the smpthost
string username = "Username";
string passwd = "xxxxxx";
string smtpHost = "mail.bankofamerica.com";
SmtpClient ss = new SmtpClient ();
ss.EnableSsl= true;
ss.Host = smtpHost;
ss.Credentials = new NetworkCredential ( username, passwd );
ss.Send ( objMail );
}
Sigaba Secure Email secures e-mail from client to client through the use of desktop plug-ins and Web-based authentication and decryption.

Related

Gmail SMTP failure using c# SmtpClient

Our application has the possibility to send emails via SmtpClient. One of our customer is trying to do so by using his gmail account and it fails resulting in a timeout. However, from our testing lab it works just fine (with another gmail account).
In the trace i can see that the server is not answering with Certificate, Server Key Exchange, Server Hello Done. And im wondering what can be the cause for this?
I also noticed in the traces, the customer is using TLSv1 so I tried to replicate the error on a Windows7 system but still it works for me.
oSmtp = new SmtpClient(this.host, this.port);
oSmtp.DeliveryMethod = SmtpDeliveryMethod.Network;
oSmtp.EnableSsl = ssl;
NetworkCredential oCredential = new NetworkCredential(this.userName, this.password);
oSmtp.Credentials = oCredential;
oSmtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userState = null;
oSmtp.SendAsync(oMsg, userState);
As far as the code goes, enableSsl is true, the port is 587 and we also instructed our customer to check his gmail account and allow less secure applications.
We will ask the customer for more specific details and try to put more traces in our application, but i would like to know if there is anything that can prevent the server to answer with Certificate,...
Inspecting the traces revealed no significant difference between customers Client Hello and our test Client Hello.
Thanks!
This is a working sample i used few days ago:
string fromAddress = "fromaddress#gmail.com";
var toAddress = new MailAddress("fake#email.com", "To person");
const string fromPassword = "pass";
const string subject = "test";
const string body = "Hey now!!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(fromAddress);
mail.To.Add(toAddress);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
//mail.Attachments.Add(new Attachment("C:\\file.zip"));
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
also make sure to enable Less secure app access for the gmail you are using to send data:

The SMTP server requires a secure connection

I am using MVC framework 4.5 C# and publish the my project on Windows server 2012 R2. In that server when I tried to sending mail with gmail but its can not send the mail and giving the below description.
The SMTP server requires a secure connection or the client was not
authenticated.The server response was: 5.5.1 Authentication Required.
I installed SMTP Service and all configuration regarding that.
Same mail configuration is running my development server.
It is due to security check on gmail so please follow below steps.
Log in to production server via remote access, and sign in to gmail once with your credentials. They will ask for the confirmation, confirm it
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Credentials = new System.Net.NetworkCredential("your email address", "password");
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
// Specify the email sender.
// Create a mailing address that includes a UTF8 character
// in the display name.
MailAddress from = new MailAddress("your email address");
// Set destinations for the email message.
MailAddress to = new MailAddress(textBox_SedToEmail.Text);
// Specify the message content.
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test email message sent by an application. ";
// Include some non-ASCII characters in body and subject.
string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
message.Body += Environment.NewLine + someArrows;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "test message 1" + someArrows;
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.Attachments.Add(new Attachment(#"C:\Users\eddie\Pictures\2.jpg"));
// Set the method that is called back when the send operation ends.
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
// The userState can be any object that allows your callback
// method to identify this send operation.
// For this example, the userToken is a string constant.
string userState = "test message1";
client.SendAsync(message, userState);

Sending emails through mvc

I am creating my mvc app. I would like to send email to users that register. I do it like this:
MailMessage mail = new MailMessage();
mail.To.Add(user1.email.Replace(" ", string.Empty));
mail.From = new MailAddress("declarations#virtual.mini.pw.edu.pl");
mail.Subject = "Class Declaration System user creation confirmation.";
string body = "Dear " + user1.name + ",\n This is to confirm that you have succesfully registered in the system. \n Do not reply to this message. \n Regards";
mail.Body = body;
mail.IsBodyHtml = true;
var smtp = new SmtpClient();
smtp.EnableSsl = true;
smtp.Host = "poczta.mini.pw.edu.pl";
smtp.Port = 25;
And everything seems fine. I have contacted the administrator of the server and I am sending everything through a right port. However, I get an error:
Command parameter not implemented. The server response was: 5.5.2
> <WIN-KI3H68FIO4E>: Helo command rejected: need fully-qualified hostname
The administrator told me that this is because I am trying to send it as WIN-KI3H68FIO4E, but it should be something.mini.pw.edu.pl, since we have such restrictions here. How do I change it in my code?
The answer was to edit the web.config file and to add there custom ClientDomain.

Email not working,Not able to receive email for yahoo email id

I am stuck and not able to receive email from yahoo id(if the sender email id is of yahoo).
code is working fine not giving me any error and i am receiving email fromm gmail id.
i am using localhost (not in local machine on live server).
hosting server : smtp.snapgrid.com
also used authentication,enable ssl , using proper port for ssl.
on snapgrid i do check so i got is mail from yahoo is blocked and the message is,
message :
Type: blocked
Reason: 550 5.7.1 Unauthenticated email from yahoo.com is not accepted due to domain's
DMARC policy. Please contact administrator of yahoo.com domain if this was a legitimate
mail. Please visit http://support.google.com/mail/answer/2451690 to learn about DMARC
initiative.
please help...
code i used to send is(its working fine just giving for idea):
Method 1:
SmtpClient objSMTPClient = new SmtpClient();
objSMTPClient.Host = ConfigurationManager.AppSettings["strSMTPServer"];
string BODY_FORMAT = ConfigurationManager.AppSettings["EmailBodyContentFormat"];
MailMessage objMailMessage = new MailMessage(from.Trim(), to.Trim(), subject.Trim(), body.Trim());
objSMTPClient.UseDefaultCredentials = false;
if (BODY_FORMAT.ToUpper() == "HTML")
objMailMessage.IsBodyHtml = true;
else if (BODY_FORMAT.ToUpper() == "TEXT")
{
body = StripTags(body);
objMailMessage.IsBodyHtml = false;
objMailMessage.Body = body.ToString().Trim();
}
else
return false;
objSMTPClient.Send(objMailMessage);
return true;
Method 2:
SmtpClient oMail = new SmtpClient();
MailMessage msg = new MailMessage();
MailAddress Madd = new MailAddress(from, "sunil");
oMail.Host = "smtp.gmail.com";
oMail.Port = 587;
oMail.EnableSsl = true;
oMail.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
oMail.Credentials = new NetworkCredential("sunil123#mydomain.com", "******");
oMail.Timeout = 20000;
msg.From = Madd;
msg.Body = body.ToString();
msg.To.Add(to);
msg.Subject = subject;
msg.IsBodyHtml = true;
oMail.Send(msg);
return true;
both are working having no bug running without error....
If you are sending via a server belonging to someone like Yahoo, Google or Office365 they expect the sender name of the account to match that that you're sending using in the from address.
For example, this would work on a your local SMTP server:
Message.From = new MailAddress("GrandMasterFlush#domain.com");
However, to get it to send via someone like Yahoo would require you to send it like this:
Message.From = new MailAddress("GrandMasterFlush#domain.com", "Grandmaster Flush");
If the sender name provided does not exactly match that of the account the email will not get sent.

c# Sending emails with authentication. standard approach not working

I am trying to send an email using the following very standard code. However, I get the error that follow...
MailMessage message = new MailMessage();
message.Sender = new MailAddress("sen#der.com");
message.To.Add("reci#pient.com");
message.Subject = "test subject";
message.Body = "test body";
SmtpClient client = new SmtpClient();
client.Host = "mail.myhost.com";
//client.Port = 587;
NetworkCredential cred = new NetworkCredential();
cred.UserName = "sen#der.com";
cred.Password = "correct password";
cred.Domain = "mail.myhost.com";
client.Credentials = cred;
client.UseDefaultCredentials = false;
client.Send(message);
Mailbox unavailable. The server
response was: No such
user here.
This recipient email address definitely works. To make this account work I had to do some special steps in outlook. Specifically, I had to do change account settings -> more settings -> outgoing server -> my outgoing server requires authentication & use same settings. I am wondering if there is some other strategy.
I think the key here is that my host is Server Intellect and I know that some people on here use them so hopefully someone else has been able to get through this. I did talk to support but they said with coding issues I am on my own :o
try this...
NetworkCredential cred = new NetworkCredential();
cred.UserName = "sen#der.com";
cred.Password = "correct password";
//cred.Domain = "mail.myhost.com";
... you should not need to provide the .Domain unless you are using Kerberos or some other complex authentication.
Edit...
Check out my extended answer. It has an example of how to send an email with authentication. It's also has SSL enabled so you may need to remove that part.
there is no mailbox called sen#der.com on server mail.myhost.com, check that

Categories