)>}]
شركة التطبيقات المتكاملة لتصميم وبرمجة البرمجيات الخاصة ش.ش.و.
Integrated Applications Programming Company
Home » Code Library » Smtp (Ia.Cl.Models)

Public general use code classes and xml files that we've compiled and used over the years:

SMTP Server Support Class

    1: using System.Diagnostics;
    2: using System.Net;
    3: using System.Text;
    4: using MimeKit;
    5: using MailKit.Net.Smtp;
    6: using MailKit.Security;
    7:  
    8: namespace Ia.Cl.Models
    9: {
   10:     ////////////////////////////////////////////////////////////////////////////
   11:  
   12:     /// <summary publish="true">
   13:     /// SMTP Server Support Class
   14:     /// </summary>
   15:     /// <remarks> 
   16:     /// Copyright © 2001-2024 Jasem Y. Al-Shamlan (info@ia.com.kw), Integrated Applications - Kuwait. All Rights Reserved.
   17:     ///
   18:     /// This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
   19:     /// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
   20:     ///
   21:     /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
   22:     /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
   23:     /// 
   24:     /// You should have received a copy of the GNU General Public License along with this library. If not, see http://www.gnu.org/licenses.
   25:     /// 
   26:     /// Copyright notice: This notice may not be removed or altered from any source distribution.
   27:     /// </remarks> 
   28:     public class Smtp
   29:     {
   30:         private enum SubType { Plain, Html };
   31:  
   32:         ////////////////////////////////////////////////////////////////////////////
   33:  
   34:         /// <summary>
   35:         ///
   36:         /// </summary>
   37:         public Smtp() { }
   38:  
   39:         ////////////////////////////////////////////////////////////////////////////
   40:  
   41:         /// <summary>
   42:         ///
   43:         /// </summary>
   44:         public static Ia.Cl.Models.Result SendPlain(string name, string email, string subject, string content)
   45:         {
   46:             return Send(name, email, subject, content, SubType.Plain);
   47:         }
   48:  
   49:         ////////////////////////////////////////////////////////////////////////////
   50:  
   51:         /// <summary>
   52:         ///
   53:         /// </summary>
   54:         public static Ia.Cl.Models.Result SendHtml(string name, string email, string subject, string content)
   55:         {
   56:             return Send(name, email, subject, content, SubType.Html);
   57:         }
   58:  
   59:         ////////////////////////////////////////////////////////////////////////////
   60:  
   61:         /// <summary>
   62:         ///
   63:         /// </summary>
   64:         private static Ia.Cl.Models.Result Send(string name, string email, string subject, string content, SubType mailType)
   65:         {
   66:             bool smtpServerEnableSsl;
   67:             string smtpServerHost, smtpServerUserName, smtpServerUser, smtpServerPassword;
   68:  
   69:             /* 
   70:              * appsettings.json:
   71:   "AppSettings": {
   72:     "SmtpServerEnableSsl": "false|true",
   73:     "SmtpServerHost": "*********",
   74:     "SmtpServerUserName": ""*********",",
   75:     "SmtpServerUser": "*********",
   76:     "SmtpServerPassword": "*********",
   77:   }
   78:             */
   79:  
   80:             smtpServerEnableSsl = bool.Parse(Ia.Cl.Models.ApplicationConfiguration.GetSetting("AppSettings:SmtpServerEnableSsl"));
   81:             smtpServerHost = Ia.Cl.Models.ApplicationConfiguration.GetSetting("AppSettings:SmtpServerHost");
   82:             smtpServerUserName = Ia.Cl.Models.ApplicationConfiguration.GetSetting("AppSettings:SmtpServerUserName");
   83:             smtpServerUser = Ia.Cl.Models.ApplicationConfiguration.GetSetting("AppSettings:SmtpServerUser");
   84:             smtpServerPassword = Ia.Cl.Models.ApplicationConfiguration.GetSetting("AppSettings:SmtpServerPassword");
   85:  
   86:             return Send(name, email, subject, content, smtpServerHost, smtpServerUserName, smtpServerUser, smtpServerPassword, smtpServerEnableSsl, mailType);
   87:         }
   88:  
   89:         ////////////////////////////////////////////////////////////////////////////
   90:  
   91:         /// <summary>
   92:         ///
   93:         /// </summary>
   94:         private static Ia.Cl.Models.Result Send(string name, string email, string subject, string content, string smtpServerHost, string smtpServerUserName, string smtpServerUser, string smtpServerPassword, bool smtpServerEnableSsl, SubType subType)
   95:         {
   96:             // https://github.com/jstedfast/MailKit/blob/master/Documentation/Examples/SmtpExamples.cs
   97:  
   98:             int port;
   99:             var result = new Ia.Cl.Models.Result();
  100:  
  101:             var message = new MimeMessage();
  102:  
  103:             message.From.Add(new MailboxAddress(smtpServerUserName, smtpServerUser));
  104:             message.To.Add(new MailboxAddress(name, email));
  105:             message.Subject = subject;
  106:  
  107:             if (subType == SubType.Html) message.Body = new TextPart("html") { Text = content };
  108:             else /*if (subType == SubType.Plain)*/ message.Body = new TextPart("plain") { Text = content };
  109:  
  110:             var secureSocketOptions = new SecureSocketOptions();
  111:  
  112:             if (smtpServerEnableSsl)
  113:             {
  114:                 secureSocketOptions = SecureSocketOptions.Auto;
  115:             }
  116:             else secureSocketOptions = SecureSocketOptions.None;
  117:  
  118:             port = 587;
  119:  
  120:             if (smtpServerHost == "smtp.gmail.com")
  121:             {
  122:                 port = 465;
  123:                 secureSocketOptions = SecureSocketOptions.SslOnConnect;
  124:             }
  125:  
  126:             using (var smtpClient = new SmtpClient())
  127:             {
  128:                 try
  129:                 {
  130:                     smtpClient.Connect(smtpServerHost, port, secureSocketOptions);
  131:                 }
  132:                 catch (SmtpCommandException ex)
  133:                 {
  134:                     result.AddError("Error trying to connect: " + ex.Message);
  135:                     result.AddError("StatusCode: " + ex.StatusCode);
  136:  
  137:                     return result;
  138:                 }
  139:                 catch (SmtpProtocolException ex)
  140:                 {
  141:                     result.AddError("Protocol error while trying to connect: " + ex.Message);
  142:  
  143:                     return result;
  144:                 }
  145:  
  146:                 // below: Not all SMTP servers support authentication, but GMail does.
  147:                 if (smtpClient.Capabilities.HasFlag(SmtpCapabilities.Authentication))
  148:                 {
  149:                     try
  150:                     {
  151:                         smtpClient.Authenticate(smtpServerUser, smtpServerPassword);
  152:                     }
  153:                     catch (AuthenticationException ex)
  154:                     {
  155:                         result.AddError("Invalid user name or password.");
  156:  
  157:                         return result;
  158:                     }
  159:                     catch (SmtpCommandException ex)
  160:                     {
  161:                         result.AddError("Error trying to authenticate: " + ex.Message);
  162:                         result.AddError("StatusCode: " + ex.StatusCode);
  163:  
  164:                         return result;
  165:                     }
  166:                     catch (SmtpProtocolException ex)
  167:                     {
  168:                         result.AddError("Protocol error while trying to authenticate: " + ex.Message);
  169:  
  170:                         return result;
  171:                     }
  172:                 }
  173:  
  174:                 try
  175:                 {
  176:                     smtpClient.Send(message);
  177:  
  178:                     result.AddSuccess("Email sent to " + email + ".");
  179:                 }
  180:                 catch (SmtpCommandException ex)
  181:                 {
  182:                     result.AddError("Error sending message: " + ex.Message);
  183:                     result.AddError("StatusCode: " + ex.StatusCode);
  184:  
  185:                     switch (ex.ErrorCode)
  186:                     {
  187:                         case SmtpErrorCode.RecipientNotAccepted:
  188:                             result.AddError("Recipient not accepted: " + ex.Mailbox);
  189:                             break;
  190:                         case SmtpErrorCode.SenderNotAccepted:
  191:                             result.AddError("Sender not accepted: " + ex.Mailbox);
  192:                             break;
  193:                         case SmtpErrorCode.MessageNotAccepted:
  194:                             result.AddError("Message not accepted.");
  195:                             break;
  196:                     }
  197:                 }
  198:                 catch (SmtpProtocolException ex)
  199:                 {
  200:                     result.AddError("Protocol error while sending message: " + ex.Message);
  201:                 }
  202:  
  203:                 smtpClient.Disconnect(true);
  204:  
  205:                 return result;
  206:             }
  207:         }
  208:  
  209:         ////////////////////////////////////////////////////////////////////////////
  210:         ////////////////////////////////////////////////////////////////////////////
  211:     }
  212: }