<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: GPManuel</title>
    <description>The latest articles on Forem by GPManuel (@gpmanuel).</description>
    <link>https://forem.com/gpmanuel</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F566537%2Fb52e485c-99aa-4666-8a6a-e51b5e148cda.jpg</url>
      <title>Forem: GPManuel</title>
      <link>https://forem.com/gpmanuel</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/gpmanuel"/>
    <language>en</language>
    <item>
      <title>Send emails, with html template, from Xamarin.Forms</title>
      <dc:creator>GPManuel</dc:creator>
      <pubDate>Tue, 28 Mar 2023 11:44:12 +0000</pubDate>
      <link>https://forem.com/gpmanuel/send-emails-with-html-template-from-xamarinforms-3pdp</link>
      <guid>https://forem.com/gpmanuel/send-emails-with-html-template-from-xamarinforms-3pdp</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Generally, to send an email, if this is not the nature of our application, we fall back to a third party APP that by default our device uses for this purpose.&lt;/p&gt;

&lt;p&gt;We do this using &lt;a href="https://learn.microsoft.com/en-us/xamarin/essentials/email?tabs=android" rel="noopener noreferrer"&gt;Xamarin.Essentials and the Email class&lt;/a&gt;, which allows an application to open the default email application with specified information including subject, body and recipients (TO, CC, BCC).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In this post we are going to show how to send emails from our Xamarin.Forms shared project (PCL). These emails, to give them a better appearance, we will format them using an HTML template.&lt;/p&gt;

&lt;p&gt;For our case we are going to imagine that we want to send a notification about the user's activity, without the user having to intervene.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;We could facilitate the writing of an email to the user through a view where we collect all the data and then generate the email from the backend. But that is not the goal of this post.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The emails will be sent thanks to the &lt;a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.mail?view=net-5.0" rel="noopener noreferrer"&gt;System.Net.Mail&lt;/a&gt; namespace, through SMTP protocol.&lt;/p&gt;

&lt;h2&gt;
  
  
  HTML template:
&lt;/h2&gt;

&lt;p&gt;First we will add the HTML template to our project:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;html xmlns="http://www.w3.org/1999/xhtml"&amp;gt;   
&amp;lt;head&amp;gt;  
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;  
&amp;lt;/head&amp;gt;   
&amp;lt;body&amp;gt;    
    &amp;lt;table&amp;gt;   
        &amp;lt;tr&amp;gt;   
            &amp;lt;td&amp;gt;  
                &amp;lt;br /&amp;gt;  
                &amp;lt;br /&amp;gt;   
                &amp;lt;div style="border-top:3px solid #22BCE5"&amp;gt; &amp;lt;/div&amp;gt;   
                &amp;lt;span style="font-family:Arial;font-size:10pt"&amp;gt;  

Hello &amp;lt;b&amp;gt;{UserName}&amp;lt;/b&amp;gt;,&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;    

{message}  

&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;    
Thanks&amp;lt;br /&amp;gt;    

&amp;lt;/span&amp;gt;    
            &amp;lt;/td&amp;gt;    
        &amp;lt;/tr&amp;gt;    
    &amp;lt;/table&amp;gt;    
&amp;lt;/body&amp;gt;    
&amp;lt;/html&amp;gt; 


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the properties of this resource, to make use of it, it is essential to mark the &lt;strong&gt;Compilation Action as "Embedded Resource".&lt;/strong&gt; (Build Action: EmbeddedResource). &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fogj0bo3l50ji6wft6bzp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fogj0bo3l50ji6wft6bzp.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Loading template and substituting variables
&lt;/h1&gt;

&lt;p&gt;When loading the template to read it, substitute the variables and send the content via SMTP, it is possible that we have problems to indicate the path. In another project we would write the absolute path, but we have to think that this application will be running on an Android device. So, if we want to perform this action from our shared project we will use the &lt;a href="https://docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows" rel="noopener noreferrer"&gt;Xamarin.Forms File Control&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Therefore we will locate the resource as follows:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

 var assembly = typeof(App).GetTypeInfo().Assembly;
 Stream stream = assembly.GetManifestResourceStream("Namespace.Folder.EmailTemplate.html");


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the template we can introduce variables between braces &lt;strong&gt;{}&lt;/strong&gt;, to substitute them for the content we want.&lt;/p&gt;

&lt;p&gt;Later we will use StreamReader, passing it the Stream, to read the template and substitute the variables for our content:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

string body = string.Empty;
using (StreamReader reader = new StreamReader(stream))
{
    body = reader.ReadToEnd();
}
body = body.Replace("{UserName}", user);
body = body.Replace("{message}", message);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This way we would already have the body of our email in HTML format. &lt;/p&gt;

&lt;h1&gt;
  
  
  Send email
&lt;/h1&gt;

&lt;p&gt;We will simply create a new method to send the email through SMTP:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;public void SendEmail(string asunto, string mensaje)&lt;br&gt;
        {&lt;br&gt;&lt;br&gt;
              try&lt;br&gt;
              {&lt;br&gt;
                  MailMessage mail = new MailMessage();&lt;br&gt;
                  SmtpClient SmtpServer = new SmtpClient("smtp.office365.com");&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;              mail.From = new MailAddress("emisor@mail.com");
              mail.To.Add("receptor@mail.com");
              mail.Subject = asunto;
              mail.Body = mensaje;
              mail.IsBodyHtml = true;

              SmtpServer.Port = 587;
              SmtpServer.Host = "smtp.office365.com";
              SmtpServer.EnableSsl = true;
              SmtpServer.UseDefaultCredentials = false;
              SmtpServer.Credentials = new System.Net.NetworkCredential("emisor@mail.com", "password");

              SmtpServer.Send(mail);
          }
          catch (Excepción ex)
          {
              DisplayAlert("Error", ex.Message, "OK");  
          }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Spanish post:&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://dev.to/gpmanuel/enviar-emails-con-plantilla-html-desde-xamarin-forms-43l5"&gt;Enviar emails, con plantilla html, desde Xamarin.Forms&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  References:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://www.c-sharpcorner.com/article/xamarin-forms-send-email-using-smtp2/" rel="noopener noreferrer"&gt;Xamarin.Forms - Send Email Using SMTP&lt;br&gt;
&lt;/a&gt;&lt;br&gt;
&lt;a href="https://medium.com/@durgeshbarwal/send-email-with-html-templates-using-c-eb97ba9665e5" rel="noopener noreferrer"&gt;Send Email with HTML Templates using C#&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.c-sharpcorner.com/UploadFile/33b051/sending-mail-with-html-template/" rel="noopener noreferrer"&gt;Sending Email With HTML Template&lt;br&gt;
&lt;/a&gt;&lt;br&gt;
&lt;a href="https://docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows" rel="noopener noreferrer"&gt;File control&lt;/a&gt;&lt;/p&gt;

</description>
      <category>xamarinforms</category>
      <category>html</category>
      <category>mail</category>
      <category>notification</category>
    </item>
    <item>
      <title>Enviar emails, con plantilla html, desde Xamarin.Forms</title>
      <dc:creator>GPManuel</dc:creator>
      <pubDate>Fri, 19 Mar 2021 18:34:23 +0000</pubDate>
      <link>https://forem.com/gpmanuel/enviar-emails-con-plantilla-html-desde-xamarin-forms-43l5</link>
      <guid>https://forem.com/gpmanuel/enviar-emails-con-plantilla-html-desde-xamarin-forms-43l5</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Generalmente, para mandar un correo electrónico, si esta no es la naturaleza de nuestra aplicación, recurrimos a una tercera APP que por defecto use nuestro dispositivo para este fin.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Esto lo hacemos mediante &lt;a href="https://docs.microsoft.com/es-es/xamarin/essentials/email?tabs=android" rel="noopener noreferrer"&gt;Xamarin.Essentials y la clase Email&lt;/a&gt;, que permite que una aplicación abra la aplicación de correo electrónico predeterminada con información especificada incluido el asunto, el cuerpo y los destinatarios (PARA, CC, CCO)&lt;/em&gt;. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;En esta entrada vamos a mostrar como enviar emails desde nuestro proyecto compartido(PCL) de Xamarin.Forms. Estos emails, para otorgarles una mejor apariencia, los formatearemos ayudándonos de una plantilla HTML.&lt;/p&gt;

&lt;p&gt;Para nuestro caso vamos a imaginar que queremos enviar una notificación sobre la actividad del usuario, sin que este tenga que intervenir. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Podríamos facilitar la redacción de un email para el usuario a través de una vista donde recojamos todos los datos y luego generásemos el email desde backend. Pero no es el objetivo de esta entrada.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Los emails los enviaremos gracias al espacio de nombre &lt;a href="https://docs.microsoft.com/es-es/dotnet/api/system.net.mail?view=net-5.0" rel="noopener noreferrer"&gt;System.Net.Mail&lt;/a&gt;, mediante protocolo SMTP.&lt;/p&gt;

&lt;h1&gt;
  
  
  Plantilla HTML:
&lt;/h1&gt;

&lt;p&gt;En primer lugar añadiremos la plantilla HTML a nuestro proyecto:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;html xmlns="http://www.w3.org/1999/xhtml"&amp;gt;   
&amp;lt;head&amp;gt;  
    &amp;lt;title&amp;gt;&amp;lt;/title&amp;gt;  
&amp;lt;/head&amp;gt;   
&amp;lt;body&amp;gt;    
    &amp;lt;table&amp;gt;   
        &amp;lt;tr&amp;gt;   
            &amp;lt;td&amp;gt;  
                &amp;lt;br /&amp;gt;  
                &amp;lt;br /&amp;gt;   
                &amp;lt;div style="border-top:3px solid #22BCE5"&amp;gt; &amp;lt;/div&amp;gt;   
                &amp;lt;span style="font-family:Arial;font-size:10pt"&amp;gt;  

Hello &amp;lt;b&amp;gt;{UserName}&amp;lt;/b&amp;gt;,&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;    

{message}  

&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;    
Thanks&amp;lt;br /&amp;gt;    

&amp;lt;/span&amp;gt;    
            &amp;lt;/td&amp;gt;    
        &amp;lt;/tr&amp;gt;    
    &amp;lt;/table&amp;gt;    
&amp;lt;/body&amp;gt;    
&amp;lt;/html&amp;gt; 


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;En las propiedades de este recurso, para hacer uso de el, es fundamental marcar la &lt;strong&gt;Acción de Compilación como "Recurso incrustado"&lt;/strong&gt; (Build Action: EmbeddedResource). &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fogj0bo3l50ji6wft6bzp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fogj0bo3l50ji6wft6bzp.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Cargar plantilla y sustituir variables
&lt;/h1&gt;

&lt;p&gt;A la hora de cargar la plantilla para leerla, sustituir las variables y mandar el contenido vía SMTP, es posible que tengamos problemas para indicar la ruta. En otro proyecto escribiríamos la ruta absoluta, pero hemos de pensar que esta aplicación estará corriendo en un dispositivo Android. Por lo que, si queremos realizar esta acción desde nuestro proyecto compartido haremos uso del &lt;a href="https://docs.microsoft.com/es-es/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows" rel="noopener noreferrer"&gt;Control de archivos de Xamarin.Forms&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Por lo tanto localizaremos el recurso del siguiente modo:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

 var assembly = typeof(App).GetTypeInfo().Assembly;
 Stream stream = assembly.GetManifestResourceStream("EspacioDeNombres.Carpeta.EmailTemplate.html");


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;En la plantilla podemos introducir variables entre llaves &lt;strong&gt;{}&lt;/strong&gt;, para sustituirlas por el contenido que deseemos.&lt;/p&gt;

&lt;p&gt;Posteriormente usaremos StreamReader, pasándole el Stream, para leer la plantilla y sustituir las variables por nuestro contenido:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

string body = string.Empty;
using (StreamReader reader = new StreamReader(stream))
{
    body = reader.ReadToEnd();
}
body = body.Replace("{UserName}", usuario);
body = body.Replace("{message}", mensaje);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;De este modo ya tendríamos el cuerpo de nuestro email en formato HTML. &lt;/p&gt;

&lt;h1&gt;
  
  
  Enviar email
&lt;/h1&gt;

&lt;p&gt;Sencillamente nos quedará crear un nuevo método que envíe el email a través de SMTP:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public void SendEmail(string asunto, string mensaje)
        {            
              try
              {
                  MailMessage mail = new MailMessage();
                  SmtpClient SmtpServer = new SmtpClient("smtp.office365.com");

                  mail.From = new MailAddress("emisor@mail.com");
                  mail.To.Add("receptor@mail.com");
                  mail.Subject = asunto;
                  mail.Body = mensaje;
                  mail.IsBodyHtml = true;

                  SmtpServer.Port = 587;
                  SmtpServer.Host = "smtp.office365.com";
                  SmtpServer.EnableSsl = true;
                  SmtpServer.UseDefaultCredentials = false;
                  SmtpServer.Credentials = new System.Net.NetworkCredential("emisor@mail.com", "password");

                  SmtpServer.Send(mail);
              }
              catch (Exception ex)
              {
                  DisplayAlert("Error", ex.Message, "OK");  
              }
        }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Espero que os ayude este post y sirva para contribuir a la comunidad hispano parlante.&lt;/p&gt;

&lt;p&gt;Un saludo.&lt;/p&gt;

&lt;h3&gt;
  
  
  Artículo en inglés:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://dev.to/gpmanuel/send-emails-with-html-template-from-xamarinforms-3pdp"&gt;Send emails, with html template, from Xamarin.Forms&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Referencias:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://www.c-sharpcorner.com/article/xamarin-forms-send-email-using-smtp2/" rel="noopener noreferrer"&gt;Xamarin.Forms - Send Email Using SMTP&lt;br&gt;
&lt;/a&gt;&lt;br&gt;
&lt;a href="https://medium.com/@durgeshbarwal/send-email-with-html-templates-using-c-eb97ba9665e5" rel="noopener noreferrer"&gt;Send Email with HTML Templates using C#&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.c-sharpcorner.com/UploadFile/33b051/sending-mail-with-html-template/" rel="noopener noreferrer"&gt;Sending Email With HTML Template&lt;br&gt;
&lt;/a&gt;&lt;br&gt;
&lt;a href="https://docs.microsoft.com/es-es/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows" rel="noopener noreferrer"&gt;Control de archivos&lt;/a&gt;&lt;/p&gt;

</description>
      <category>xamarinforms</category>
      <category>streamreader</category>
      <category>email</category>
      <category>resources</category>
    </item>
  </channel>
</rss>
