Reputation: 8841
Hi I want to Configure SMTP mail setting and send mail from C#.
i am using a Form and saved SMTP setting onces in a database.
whenever i want to send mail then i am using below function.
private void _MSendMail(string _pToMailId, string _pBody, string _pMailSubject = "Test Mail")
{
string _SMTPHOST = Value Come From Database;
int _SMTPPORT = Value Come From Database;
bool _ENABLESSL = Value Come From Database;
string _MAILID = Value Come From Database;
string _USERNAME = Value Come From Database;
string _PASSWORD = Value Come From Database;
using (var message = new System.Net.Mail.MailMessage())
{
message.To.Add(_pToMailId);
message.Subject = _pMailSubject;
message.From = new System.Net.Mail.MailAddress(_MAILID);
message.Body = _pBody;
using (var smtp = new System.Net.Mail.SmtpClient())
{
smtp.Host = "smtp." + _SMTPHOST + ".com";
smtp.Port = _SMTPPORT;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(_USERNAME, _PASSWORD);
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.EnableSsl = _ENABLESSL;
try
{
smtp.Send(message);
}
catch (Exception e) { }
}
}
}
My Question is: is this function right or do some change in it ??.. I tested it with Gmail it works. I need your suggestion on other mail providers same function will work or any other change is required.
Upvotes: 0
Views: 747
Reputation: 251
There are a number of things that you have to consider:
The code only sends mail to single person. Instead use IList _pToMailId and loop it as follows:
foreach (var to in _pToMailId)
{
message .To.Add(to);
}
You can repead this for CC and BCC respectively.
Upvotes: 2
Reputation: 7192
No, it is not correct. For one thing, you cannot assume that all SMTP servers are of the form "smtp.example.com". What about "example.net"? What about "mail.example.com"?
I recommend having your database store the full SMTP host address. Don't do any computation on that value.
Upvotes: 4