I A Khan
I A Khan

Reputation: 8841

How to configure SMTP mail setting

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

Answers (2)

Bikal Bhattarai
Bikal Bhattarai

Reputation: 251

There are a number of things that you have to consider:

  1. Dont fetch the smpt parameters from database inside the function. Pass the parameters to the function. This will helps if you want to send many emails repeatedly and you don't have to connect to database each time.
  2. Don't suppress the exception. Log it or throw the exception so that outer module can handle it.
  3. As said earlier by c45207, store the full SMPT host address in the database.
  4. 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

chwarr
chwarr

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

Related Questions