How can I send an email using an xml file?

0

I have a program written in C # which has to send an email. What I'm looking for is that the content of the email comes from an xml file.

Here is how I have the code of the post office:

MailMessage mail = new MailMessage("[email protected]", "[email protected]");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "localhost"; 
mail.Subject = "Testing email";
mail.Body = "This is a test email";
client.Send(mail); 

How could I do that? Is there any better way to handle the content of the mail than to modify the string every time you need to make changes?

Greetings,

    
asked by A arancibia 27.02.2017 в 17:48
source

1 answer

1

To tackle the problem you have what you need to do are the following steps.

To save the data in an xml:

  • Create a class that contains the data
  • Serialize the class
  • Save the serialized in a file
  • To recover the data:

  • Read and deserialize the file
  • Use the data
  • For example to save the data of your email you can use this class:

    public class EmailData
    {
        public string MailTo { get; set; }
        public string MailFrom { get; set; }
        public int Port { get; set; }
        public SmtpDeliveryMethod SmtpDeliveryMethod { get; set; }
        public bool UseDefaultCredentials { get; set; }
        public string Host { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
    }
    

    To serialize and deserialize objects you can use these extensions that I created:

     public static class SerializerExtensions
     {
        public static void SerializarYGuardar(this object value, string ruta)
        {
            try
            {
                var xmlserializer = new XmlSerializer(value.GetType());
                var stringWriter = new StringWriter();
                using (XmlWriter writer = XmlWriter.Create(stringWriter))
                {
                    xmlserializer.Serialize(writer, value);
                    StreamWriter strWr = File.CreateText(ruta);
                    strWr.Write(stringWriter);
                    strWr.Close();
                    strWr.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Se ha producido un error", ex);
            }
        }
    
    
        public static T DesSerialize<T>(string rutafichero)
        {
            try
            {
                using (StreamReader streamRead = new StreamReader(rutafichero))
                {
                    var xmlserializer = new XmlSerializer(typeof(T));
                    object obj = xmlserializer.Deserialize(streamRead);
    
                    if (obj is T)
                        return (T)obj;
                    else
                        throw new Exception("El objeto deserializado no es del tipo indicado");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Ha ocurrido un error:", ex);
            }
        }
    
    
    }
    

    And an example of all this working would be:

    class Program
    {
        static void Main(string[] args)
        {
            string rutaFichero = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "correo.xml");
    
            EmailData emData = new ConsoleApplication2.EmailData()
            {
                Body = "mensaje...",
                Host = "el host",
                MailFrom = "[email protected]",
                MailTo = "[email protected]",
                Port = 22,
                SmtpDeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
                Subject = "subject",
                UseDefaultCredentials = false
    
            };
    
            emData.SerializarYGuardar(rutaFichero);
    
            EmailData result = SerializerExtensions.DesSerialize<EmailData>(rutaFichero);
    
        }
    
    }
    

    After doing EmailData result = SerializerExtensions.DesSerialize<EmailData>(rutaFichero); you will already have the data loaded so you can fill in your email with them.

        
    answered by 01.03.2017 в 09:53