Aide pour améliorer une classe SMTP

cs_Yanith Messages postés 34 Date d'inscription mercredi 26 octobre 2005 Statut Membre Dernière intervention 24 septembre 2014 - 7 juil. 2011 à 21:28
cs_Yanith Messages postés 34 Date d'inscription mercredi 26 octobre 2005 Statut Membre Dernière intervention 24 septembre 2014 - 8 juil. 2011 à 14:48
Bonjour,

Je voudrait déjà commencer pas dire que je trouve beaucoup d'inspiration sur se site, cela m'aide beaucoup dans mon travail. Je n'ai pas pour habitude de demander de l'aide, mais il se trouve que je voudrait mieux comprendre et améliorer une class que j'ai trouvé et modifié.

J'ai trouvé une class à cette adresse que j'ai modifié.

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Collections;
using System.Windows.Forms;

namespace WatT.Sx
{
    public class C_SMTP : C_Email, IDisposable
    {
        private string _SMTPServer;
        private int _SMTPServerPort;

        private List<string> _To;
        private List<string> _CC;
        private List<string> _Bcc;
        private string _From;
        private string _FromName;
        private string _Subject;
        private string _Body;
        private List<MyEmailAttachment> Attachments;
        private int _Priority;

        private bool _UsingSMTPAuth;
        private string _SMTPUser;
        private string _SMTPPassword;
        private string _SMTPDomain;
        private bool _UsingSSL;

        public string SMTPServer { get { return this._SMTPServer; } set { this._SMTPServer = value; } }
        public int SMTPServerPort { get { return this._SMTPServerPort; } set { this._SMTPServerPort = value; } }

        public List<string> To { get { return this._To; } set { this._To = value; } }
        public List<string> CC { get { return this._CC; } set { this._CC = value; } }
        public List<string> Bcc { get { return this._Bcc; } set { this._Bcc = value; } }
        public string From { get { return this._From; } set { this._From = value; } }
        public string FromName { get { return this._FromName; } set { this._FromName = value; } }
        public string Subject { get { return this._Subject; } set { this._Subject = value; } }
        public string Body { get { return this._Body; } set { this._Body = value; } }
        public int Priority { get { return this._Priority; } set { this._Priority = value; } }

        public bool UsingSMTPAuth { get { return this._UsingSMTPAuth; } set { this._UsingSMTPAuth = value; } }
        public string SMTPUser { get { return this._SMTPUser; } set { this._SMTPUser = value; } }
        public string SMTPPassword { get { return this._SMTPPassword; } set { this._SMTPPassword = value; } }
        public string SMTPDomain { get { return this._SMTPDomain; } set { this._SMTPDomain = value; } }
        public bool UsingSSL { get { return this._UsingSSL; } set { this._UsingSSL = value; } }

        public void Dispose()
        {
            Attachments.Clear();
            To.Clear();
            CC.Clear();
            Bcc.Clear();
        }

        public C_SMTP()
        {
            Attachments = new List<MyEmailAttachment>();
        }

        public bool AddAttachment(string FileName)
        {
            if (!File.Exists(FileName))
                throw new MySMTPEmailException("Attachment file does not exist");

            try
            {
                Attachment data = new Attachment(FileName, MediaTypeNames.Application.Octet);
                ContentDisposition disposition = data.ContentDisposition;
                disposition.CreationDate = File.GetCreationTime(FileName);
                disposition.ModificationDate = File.GetLastWriteTime(FileName);
                disposition.ReadDate = File.GetLastAccessTime(FileName);
                MyEmailAttachment Attachment = new MyEmailAttachment();
                Attachment.AttachmentData = data;
                Attachment.Disposition = disposition;
                Attachments.Add(Attachment);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void SendMail()
        {
            if (To.Count <= 0)
                throw new MySMTPEmailException("Adresse mail du destinataire ne peux être vide !");
            if (From == "")
                throw new MySMTPEmailException("Adresse mail de l'expéditeur ne peux être vide !");
            if (Subject == "")
                throw new MySMTPEmailException("Le sujet ne peux être vide !");
            if (Body == "")
                throw new MySMTPEmailException("Le corps du message ne peux être vide !");
            if (SMTPServer == "")
                throw new MySMTPEmailException("l'adresse SMTP ne peux être vide !");

            MailMessage mail = new MailMessage();
            switch (_Priority)
            {
                case 0:
                    mail.Priority = MailPriority.Low;
                    break;
                case 1:
                    mail.Priority = MailPriority.Normal;
                    break;
                case 2:
                    mail.Priority = MailPriority.High;
                    break;
                default:
                    mail.Priority = MailPriority.Normal;
                    break;
            }

            foreach (string address in To)
            { mail.To.Add(address); }

            if (CC != null)
            {
                if (CC.Count > 0) 
                {    foreach (string address in CC)
                    { mail.CC.Add(address); }
                }
            }
            if (Bcc != null)
            {
                if (Bcc.Count > 0)
                {
                    foreach (string address in Bcc)
                    { mail.Bcc.Add(address); }
                }
            }
            if (Attachments != null)
            {
                if (Attachments.Count > 0)
                {
                    foreach (MyEmailAttachment Attachment in Attachments)
                    { mail.Attachments.Add(Attachment.AttachmentData); }
                }
            }
            mail.Subject = Subject;
            mail.Body = Body;
            mail.From = new MailAddress(From, FromName);

            SmtpClient client = new SmtpClient(SMTPServer, SMTPServerPort);
            if (_UsingSMTPAuth)
            {
                if (_SMTPDomain != "" && _SMTPDomain != null)
                    client.Credentials = new NetworkCredential(_SMTPUser, _SMTPPassword, _SMTPDomain);
                else
                    client.Credentials = new NetworkCredential(_SMTPUser, _SMTPPassword);
                
                if (_UsingSSL)
                    client.EnableSsl = true;
            }
            try
            {
                client.Send(mail);
            }
            catch (SmtpException ex)
            {
                throw new MySMTPEmailException(ex.Message);
            }
        }
    }

    public class C_Email
    {
        public enum EmailPriority
        {
            Low = 0,
            Normal,
            High,
        };

        protected struct MyEmailAttachment
        {
            public Attachment AttachmentData;
            public ContentDisposition Disposition;
        }
    }

    public class MySMTPEmailException : Exception
    {
        public MySMTPEmailException()
            : base()
        { }
        public MySMTPEmailException(string Message)
            : base(Message)
        { }
        public MySMTPEmailException(string Message, Exception Cause)
            : base(Message, Cause)
        { }
    }
}


On éxécute la classe comme ceci :

            try
            {
                C_SMTP CSMTP = new C_SMTP();
                CSMTP.SMTPServer = TextBoxSMTP_Server.Text;
                CSMTP.SMTPServerPort = Convert.ToInt16(TextBoxSMTP_Port.Text);
                CSMTP.From = TextBoxSMTP_Address.Text;
                CSMTP.FromName = TextBoxSMTP_Name.Text;
                List<string> Tox = new List<string>();
                Tox.Add(TextBoxSMTP_SendTestMailAddress.Text);
                CSMTP.To = Tox;
                CSMTP.Subject = TextBoxSMTP_Subject.Text;
                CSMTP.Body = "Message test";
                if (CheckBoxSMTP_Authentification.Checked)
                {
                    CSMTP.UsingSMTPAuth = true;
                    CSMTP.SMTPUser = TextBoxSMTP_User.Text;
                    CSMTP.SMTPPassword = TextBoxSMTP_Password.Text;
                    CSMTP.SMTPDomain = TextBoxSMTP_Domain.Text;
                    if (CheckBoxSMTP_SSL.Checked)
                        CSMTP.UsingSSL = true;
                }
                CSMTP.Priority = ComboBoxSMTP_Priority.SelectedIndex;
                CSMTP.SendMail();
            }
            catch (MySMTPEmailException ex)
            {
                MessageBox.Show(ex.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }



Je voudrait déjà modifier les points suivants :
- Convertir dans la class le port du serveur SMTP
- Pouvoir simplifier l'ajout des adresses des destinataires (du genre : CSMTP.To.Add("adresse mail");) Idem pour CC, CCi et les pièces jointes.
- et puis pour finir employé la meilleur technique pour optimiser cette class.

Pour info, je suis débutant et ne soyez pas trop "complexe" dans vos explications

5 réponses

Whismeril Messages postés 19029 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 26 avril 2024 656
7 juil. 2011 à 22:08
Bonsoir

quand tu dis :
Convertir dans la class le port du serveur SMTP
, tu entends que
CSMTP.SMTPServerPort Convert.ToInt16(TextBoxSMTP_Port.Text);
ne te convient pas, préfèrerais tu
CSMTP.SMTPServerPort TextBoxSMTP_Port.Text;
?

Si oui tu peux réécrire la méthode SMTPServerPort comme ça;
public string SMTPServerPort
{ 
get { return this._SMTPServerPort.ToString(); }
set { this._SMTPServerPort = Convert.ToInt16(value); } 
}


Pour l'ajout, essaye de déclarer _To comme ça:
private List<string> _To = new List<string>();


je ne suis pas sûr que ça fonctionne.
Sinon (et là je suis sûr), pas de _To, et déclare To comme ça:
public List<string> To = new  List<string>();


Quand à l'optimisation, ce n'est pas mon fort, désolé.
Whismeril
0
Whismeril Messages postés 19029 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 26 avril 2024 656
7 juil. 2011 à 22:10
je reviens sur le numéro de port, la variable interne est déclarée:
private int _SMTPServerPort;
, c'est donc un int32 pourquoi la convertir en int16?

Bonne soirée

Whismeril
0
cs_Yanith Messages postés 34 Date d'inscription mercredi 26 octobre 2005 Statut Membre Dernière intervention 24 septembre 2014
7 juil. 2011 à 22:25
parfait, je viens de tester t'es conseils et cela marche à merveille .
Pour le

public string SMTPServerPort
{ 
get { return this._SMTPServerPort.ToString(); }
set { this._SMTPServerPort = Convert.ToInt16(value); } 
}


j'aurais du y penser plus tot, comme pour le

private List<string> _To = new List<string>();


quand je me m'y met je bloque sur des connerie.

Je viens aussi de le remplacer le Convert.ToInt16 par Convert.ToInt32 et cela fonctione toujours. Mais je savait pas que quand tu déclarer une var en int c'était obligatoirement en Int32. J'ai surement raté plein de truc dans mon apprentissage .

Je te remercie pour ta réponce super rapide
J'attend de voir si quelqu'un d'autre à des propositions pour l'optimisation.
0
sebmafate Messages postés 4936 Date d'inscription lundi 17 février 2003 Statut Membre Dernière intervention 14 février 2014 37
8 juil. 2011 à 11:28
Hello,

A la lecture de ta classe, je pense que tu viens du monde C++.

Je te conseille de relire les conventions de nommage propre à C# et .net, ça sera beaucoup plus lisible qu'actuellement.

Quant au int, c'est un alias de System.Int32, pour obtenir un System.Int16, il faut que tu utilises un short.

Une petite lecture à te recommander : C# pour les développeurs C++


Sébastien FERRAND
Ingénieur Concepteur Senior
Microsoft Visual C# MVP 2004 - 2009
Blog Photo
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
cs_Yanith Messages postés 34 Date d'inscription mercredi 26 octobre 2005 Statut Membre Dernière intervention 24 septembre 2014
8 juil. 2011 à 14:48
salut,

merci c'est sympa, ça pourra m'aider à comprendre un peu mieux.
Et non je ne viens pas du monde C++
0
Rejoignez-nous