Send emails, with html template, from Xamarin.Forms
Tags: xamarinforms, html, mail, notification
Published: 2023-03-28 11:44:12

>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](https://learn.microsoft.com/en-us/xamarin/essentials/email?tabs=android), 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](https://learn.microsoft.com/en-us/dotnet/api/system.net.mail?view=net-5.0) 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> 
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ogj0bo3l50ji6wft6bzp.png)

#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](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows).

Therefore we will locate the resource as follows:

```
 var assembly = typeof(App).GetTypeInfo().Assembly;
 Stream stream = assembly.GetManifestResourceStream("Namespace.Folder.EmailTemplate.html");
```
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);
```

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");  
              }
        }
```
###Spanish post:
[Enviar emails, con plantilla html, desde Xamarin.Forms](https://dev.to/gpmanuel/enviar-emails-con-plantilla-html-desde-xamarin-forms-43l5)

###References:
[Xamarin.Forms - Send Email Using SMTP
](https://www.c-sharpcorner.com/article/xamarin-forms-send-email-using-smtp2/)
[Send Email with HTML Templates using C#](https://medium.com/@durgeshbarwal/send-email-with-html-templates-using-c-eb97ba9665e5)
[Sending Email With HTML Template
](https://www.c-sharpcorner.com/UploadFile/33b051/sending-mail-with-html-template/)
[File control](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows)