This question already has answers here:
Sending email through Gmail SMTP server with C#
(31 answers)
Closed 9 years ago.
I am New in Asp.net, i need to send email from Asp.net using my Outlook.
I have one button in asp and when i click button(send) i want to send email.
I tried to use Hotmail and Gmail but remote server in blocked.
If you don't understand my question please tell me.
I tried this:
var smtpClient = new SmtpClient
{
Host = "outlook.mycompany.local",
UseDefaultCredentials = false,
Credentials = new NetworkCredential("myEmail#mycommpany.com", "myPassword")
};
var message = new System.Net.Mail.MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("myemail#mycommapny.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("friendEmail#Company.com"));
// and here you're actually sending the message
smtpClient.Send(message);
}
Exeption Show: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated
Please how can i do that ?
Sending outbound email from an ASP.net web site can be problematic. Even if you get the SMTP information right, you still have to deal with:
Sender Policy Framework (SPF)
Whitelists/Blacklists
Validation
Bouncebacks
It's very difficult to do this yourself, which is why you might want to consider using a service provider instead. You simply use their API (often a REST call), and they do the rest. Here are three such providers:
SendGrid
Mandrill
Mailgun
Mandrill has a low-end free plan, and so does SendGrid if you are using it with Windows Azure. And they are all reasonably affordable, even for the larger plans.
I highly recommend using one of these with their own API instead of using System.Net.Mail yourself. But if you want, they also can act as an SMTP relay for you so you can use their SMTP servers and keep your System.Net.Mail code intact.
First of all get the company SMTP server settings (from your sys admins I guess), then you can do something like this:
// setting up the server
var smtpClient = new SmtpClient
{
Host = "your.company.smtp.server",
UseDefaultCredentials = false,
EnableSsl = true, // <-- see if you need this
Credentials = new NetworkCredential("account_to_use", "password")
};
var message = new MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("from#company.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("neo#matrix.com"));
// and here you're actually sending the message
smtpClient.Send(message);
you can use this function. and one thing you have to store you email smtp login and password in web config file
/// <summary>
/// Send Email
/// </summary>
/// <param name="strFrom"></param>
/// <param name="strTo"></param>
/// <param name="strSubject"></param>
/// <param name="strBody"></param>
/// <param name="strAttachmentPath"></param>
/// <param name="IsBodyHTML"></param>
/// <returns></returns>
public Boolean sendemail(String strFrom, string strTo, string strSubject, string strBody, string strAttachmentPath, bool IsBodyHTML)
{
Array arrToArray;
char[] splitter = { ';' };
arrToArray = strTo.Split(splitter);
MailMessage mm = new MailMessage();
mm.From = new MailAddress(strFrom);
mm.Subject = strSubject;
mm.Body = strBody;
mm.IsBodyHtml = IsBodyHTML;
//mm.ReplyTo = new MailAddress("replyto#xyz.com");
foreach (string s in arrToArray)
{
mm.To.Add(new MailAddress(s));
}
if (strAttachmentPath != "")
{
try
{
//Add Attachment
Attachment attachFile = new Attachment(strAttachmentPath);
mm.Attachments.Add(attachFile);
}
catch { }
}
SmtpClient smtp = new SmtpClient();
try
{
smtp.Host = ConfigurationManager.AppSettings["MailServer"].ToString();
smtp.EnableSsl = true; //Depending on server SSL Settings true/false
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["MailUserName"].ToString();
NetworkCred.Password = ConfigurationManager.AppSettings["MailPassword"].ToString();
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;//Specify your port No;
smtp.Send(mm);
return true;
}
catch
{
mm.Dispose();
smtp = null;
return false;
}
}
Try Amazon Simple Email Service (http://aws.amazon.com/ses/). If you're new to Amazon Web Services (AWS) there might be a learning curve. However, once you're familiar with their SDK which can be found on Nuget (AWSSDK) the process is very straight-forward (Amazon does have a lot of little wrapper classes which can be quirky).
So, to answer the question "How to send email?", it looks something like:
var fromAddress = "from#youraddress.com";
var toAddresses = new Amazon.SimpleEmail.Model.Destination("someone#somedestination.com");
var subject = new Amazon.SimpleEmail.Model.Content("Message");
var body= new Body(new Amazon.SimpleEmail.Model.Content("Body"));
var message = new Message(subject , body);
var client = ConfigUtility.AmazonSimpleEmailServiceClient;
var request= new Amazon.SimpleEmail.Model.SendEmailRequest();
request.WithSource(fromAddress)
.WithDestination(toAddresses)
.WithMessage(message );
try
{
client.SendEmail(request);
}
catch (Amazon.SimpleEmail.AmazonSimpleEmailServiceException sesError)
{
throw new SupplyitException("There was a problem sending your email", sesError);
}
You can refer to below links:
http://www.codeproject.com/Tips/371417/Send-Mail-Contact-Form-using-ASP-NET-and-Csharp
send email asp.net c#
I hope it will help you. :)
Related
I have attempted to send an email using the GMail SMTP, and followed the guides on various other questions but I still cannot get emails to send from my GMail account.
This is the code I'm using:
protected void emailSend_Click(object sender, EventArgs e)
{
var fromAddress = new MailAddress(inputEmail.Text, inputName.Text);
var toAddress = new MailAddress("spikey666#live.co.uk", "Liane Stevenson");
const string fromPassword = "*********";
const string subject = "Web Dev Wolf Message";
var body = inputMessage.Text;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("webdevelopwolf#gmail.com", fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
These are the things I've checked so far:
Turning on less secure apps on GMail
Checked the Gmail Username and Password are correct
Debugged and checked that all text fields have values and are loaded into variables
Check other port numbers suggested by Gmail help
Turned on POP/IMAP functionality on Gmail
Is there anything else I could be missing?
Before calling SmtpClient.Send(), add:
smtp.UseDefaultCredentials = false;
According to the MSDN SmtpClient page, UseDefaultCredentials is set to false by default, but there seems to be a bug somewhere that is setting it to true. Explicitly set it to false before sending the message and it should be all set.
I am trying to send email like this
var fromAddress = new MailAddress("fromaddress", "From Name");
var toAddress = new MailAddress("toaddress", "To Name");
const string fromPassword = "password";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Console.WriteLine("Sent");
Console.ReadLine();
but it gives this error .
The SMTP server requires a secure connection or the client was not authenticated.
The server response was: 5.5.1 Authentication Required.
I am sing this code in simple console application on my local host . So whats the issue in my code ?
Update
I changed fromAddress email and it send email successfully . But i don't receive any email in my toAddress email's inbox/Spam .
Try to add DeliveryMethod = SmtpDeliveryMethod.Network when creating SmtpClient.
See post:
https://stackoverflow.com/a/489594/1432770
There is a variety of reasons for this discussed here:
Sending email through Gmail SMTP server with C#
Your code in the first link has worked for me.
Do you use two steps verification?
You need to sign in using application-specific passwords: https://support.google.com/accounts/answer/185833?hl=en
Your code worked for me too!
REMAKING QUESTION
This code doesn't work
The error is: The remote certificate is invalid according to the validation procedure.
var client = new SmtpClient("smtp.domain.com.br", 25000)
{
Credentials = new NetworkCredential("username", "password"),
EnableSsl = true
};
client.Send("emailfrom#domain.com.br", "emailto#gmail.com", "test", "testbody");
// I also tested like this
// client.Send("emailfrom#domain.com.br", "emailto#domain.com", "test", "testbody");
But this code works
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("username", "password"),
EnableSsl = true
};
client.Send("emailfrom#domain.com.br", "emailto#gmail.com", "test", "testbody");
I tested the first code data in the Outlook, and works if I try to send to an email from the same domain.
I believe that the error is some SMTP configuration, but I don't know how to solve this. Any help?
which smtp server you using ?
if you are using gmail smtp server then you must use port number 587 that is required to send through gmail
based on the answer below you can pass in the values from the .config file but you will have to change what I have ..test this using hard coded values first if you like then convert the working version to use param values
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var _smtpClient = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials =
new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
_smtpClient.Send(message);
}
did you try port 465. may be you can check this article.
http://support.google.com/mail/bin/answer.py?hl=en&answer=13287
I solve this using the digital certificate generated in the outlook and putting it on the server, where my application is running.
With the code in my question plus the certificate I finally made this works.
Here is a link on How to do this: create your own digital certificate
My app is sending 3 emails at the same time to the recipient, one being the correct email, and the other two contain the subject line, but an empty message. Could this code some how cause that? If not what do you suggest?
var fromAddress = new MailAddress(domainAddress, displayName);
var toAddress = new MailAddress(oInfo.SiteUser.email, oInfo.customerName);
var Bcc = new MailAddress("deleted");
var smtp = new SmtpClient
{
Host = SmtpHost(),
Port = SmtpPort(),
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(SmtpUsername(), SmtpPassword())
};
using (var msg = new MailMessage(fromAddress, toAddress)
{
IsBodyHtml = true,
Subject = "Confirmation for your recent order at " + displayName,
Body = body
})
{
msg.Bcc.Add(Bcc);
smtp.Send(msg);
}
No, that code won't send more than one mail.
Either you have some more code that is sending mail, or you are executing that code three times, but with different values for body.
The only problem I can see with that code is the line
var Bcc = new MailAddress("deleted");
but I assume you modified it for posting here?
I can't see an issue that would cause what you're seeing. I'd check the headers in the emails for clues. Also capturing network traffic on the machine sending the emails could help.
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.