Generate an html template for email

Eduardo Gomez 3,651 Reputation points
2024-01-03T01:49:01.3866667+00:00

Hello everyone, happy new year

I have a viewModel, that generates mettings

   [RelayCommand]
   async Task StartMeeting() {

       if(string.IsNullOrEmpty(RoomName)) {
           await appService.DisplayAlert("Error", "You cannot create a Lecture without a name", "OK");
           return;
       }

       var loogedUser = await authenticationService.GetLoggedInUser();

       var databaseUer = await dataService.GetByUidAsync<User>("Users", loogedUser!.Uid);

       var meetingOptions = new MeetingOptions {
           EnableAdvancedChat = true,
           EnableEmojiReactions = true,
           EnableNoiseCancellationUi = true,
           EnableHandRaising = true,
           EnablePrejoinUi = true,
           EnablePipUi = true,
           EnableScreenshare = true,
           EnableVideoProcessingUi = true,
           EnablePeopleUi = true,
           EnableChat = true
           // Set other meeting option properties as needed
       };

       try {
           var roomURL = await meetingService.CreateMeetingAsync(RoomName, meetingOptions, Constants.DAILY);

           foreach(var userInvited in Invited) {
               string userEmail = userInvited.Email;
               await EmailHelper.SendEmail(userEmail, RoomName, databaseUer, roomURL, null);
           }

       } catch(Exception ex) {
           // Handle any exceptions that might occur during the meeting creation
           Console.WriteLine($"Error creating meeting: {ex.Message}");
       }
   }

I have created an emailHelper

    private static string GenerateHttmlTemplate(string roomName, string meetingLink, string userName, DateTime? dateTime = null) {


        string htmlBody = $@"
            <!DOCTYPE html>
            <html>
            <head>
                <style>
                    .button {{
                        background-color: #5C3E88; /* Button background color */
                        color: white; /* Text color */
                        text-decoration: none;
                        padding: 10px 20px; /* Padding around text */
                        border-radius: 5px; /* Rounded corners */
                        display: inline-block;
                    }}
                </style>
            </head>
            <body>
                <p>Here are the meeting details:</p>
                <br> <!-- Add a line break -->
                <p><strong>Meeting Name:</strong> {roomName}</p>
                <p><strong>Teacher Name:</strong> {userName}</p>
                <p>Click the button below to join the meeting:</p>
                <p><a class='button' href='{meetingLink}'>Join</a></p>";

        if(dateTime.HasValue) {
            htmlBody += $@"
                <p><strong>Date and Time:</strong> {dateTime.Value}</p>";
            // You can format the DateTime value as needed, e.g., dateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
        }

        htmlBody += @"
            </body>
            </html>";

        return htmlBody;

    }

    public static async Task SendEmail(string userEmail, string roomName, Models.User? user, string meetingLink, DateTime? dateTimeMeeting) {

        var mail = new MailMessage("******@gmail.com", userEmail) {
            Subject = "DemyIA meeting",
            IsBodyHtml = true
        };

        var body = GenerateHttmlTemplate(roomName, meetingLink, user!.Name, dateTimeMeeting);

        mail.Body = body;

        var smtpClient = new SmtpClient("smtp.gmail.com") {
            EnableSsl = true,
            UseDefaultCredentials = false,
            Credentials = new System.Net.NetworkCredential("******@gmail.com", "svzq gwda mnwc rwvz"),
            Port = 587,
        };

        await smtpClient.SendMailAsync(mail);

    }
}

The problem is that it only put the link and the purple button on the first email I send, and on the third and fifth, is not consistent..

This is when I send it for the first time.

User's image

this is the second time

User's image

is quite random

Do not worry you are only seeing the junk mail

https://reccloud.com/u/u711k5v

Developer technologies .NET .NET MAUI
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. akash pant 0 Reputation points
    2024-01-05T07:58:48.3266667+00:00

    The inconsistency you're experiencing with the link and purple button appearing only in the first email might be due to the HTML generation or email-sending process.
    it seems that the email content generation and sending are within a static method SendEmail of your EmailHelper class. It's crucial to ensure that the HTML content is consistently generated for each email being sent.

    Here are a few suggestions to investigate and potentially resolve the issue:

    1. Check Loop Iteration: Ensure that the loop iterating through the Invited list is properly structured. Verify that the loop is functioning correctly and that each iteration receives the correct parameters for generating the email content.

    2. Data Consistency: Double-check the data being passed to the EmailHelper.SendEmail method for each iteration. Ensure that the roomName, meetingLink, user.Name, and dateTimeMeeting values are correctly populated and consistent for every iteration.

    3. HTML Template: Review the HTML template generation (GenerateHttmlTemplate method) to confirm that it generates the HTML content consistently for all emails. Ensure that all necessary elements, including the link and purple button, are consistently added to the email body.

    4. Debugging: To debug and identify the issue, you could add logging or console outputs within the loop where emails are being sent. Log the parameters being passed to the SendEmail method for each iteration to check for any discrepancies.

    5. Exception Handling: Implement proper exception handling within the email-sending process. Check if any exceptions are being thrown during the email-sending process that might interrupt the consistent generation of emails.

    Additionally, the issue might stem from any asynchronous behavior or potential race conditions. Ensure that the SendEmail method is awaited properly within the loop to guarantee sequential email sending and prevent any concurrency issues.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.