DEV Community

GPManuel
GPManuel

Posted on

Send emails, with html template, from Xamarin.Forms

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.

We do this using Xamarin.Essentials and the Email class, which allows an application to open the default email application with specified information including subject, body and recipients (TO, CC, BCC).

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.

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.

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.

The emails will be sent thanks to the System.Net.Mail namespace, through SMTP protocol.

HTML template:

First we will add the HTML template to our project:

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

Hello <b>{UserName}</b>,<br /><br />    

{message}  

<br /><br />    
Thanks<br />    

</span>    
            </td>    
        </tr>    
    </table>    
</body>    
</html> 
Enter fullscreen mode Exit fullscreen mode

In the properties of this resource, to make use of it, it is essential to mark the Compilation Action as "Embedded Resource". (Build Action: EmbeddedResource).

image

Loading template and substituting variables

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 Xamarin.Forms File Control.

Therefore we will locate the resource as follows:

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

In the template we can introduce variables between braces {}, to substitute them for the content we want.

Later we will use StreamReader, passing it the Stream, to read the template and substitute the variables for our content:

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

This way we would already have the body of our email in HTML format.

Send email

We will simply create a new method to send the email through SMTP:

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 (Excepción ex)
              {
                  DisplayAlert("Error", ex.Message, "OK");  
              }
        }
Enter fullscreen mode Exit fullscreen mode

Spanish post:

Enviar emails, con plantilla html, desde Xamarin.Forms

References:

Xamarin.Forms - Send Email Using SMTP

Send Email with HTML Templates using C#
Sending Email With HTML Template

File control

Top comments (0)