2
votes

I have a razor component in my Blazor project where when user click a button it will trigger email The button

The OnClick function Email will send email, through the below code

async Task Email(string originalpiv, string docno, string cuscode, string cusname, string docdate)
{
   CModule.SendMail("[email protected]", "[email protected]", "", "HI", "HI BRO");

}

The CModule.SendMail is method where the email from,to,subj,body will be passed, below code

public static bool SendMail(string from, string to, string cc, string subject, string body)
        {
            bool rst = false;
            MailMessage Msg = new MailMessage();
            try
            {
                SmtpClient smtp = new SmtpClient("mail.gmail.com", 587);
                string[] toeml = to.Split(new Char[] { ';', ',' });
                foreach (string tmp in toeml)
                {
                    if (tmp.Trim() != "") Msg.To.Add(tmp.Trim());
                }
                string[] cceml = cc.Split(new Char[] { ';', ',' });
                foreach (string tmp in cceml)
                {
                    if (tmp.Trim() != "") Msg.CC.Add(tmp.Trim());
                }
                Msg.From = new MailAddress(from.Trim());
                Msg.Subject = subject;
                Msg.Body = body;
                Msg.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");
                smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "880215");
                smtp.Send(Msg);
                rst = true;
            }
            catch (Exception ex)
            {

            }
            finally
            {
                Msg.Dispose();
            }
            return rst;
        }

These are the code that i have tried, but the email is not sending out, not sure of why, any idea?

1
Client or server side blazor? Defone not sure why - I mean, swallowing an exception and then compaining you have no information is like not smart, you know. Do you get an exception? WHICH ONE? Bubble it up. And why do you dispose the msg in finally instead of using.... using? - TomTom

1 Answers

8
votes

Did you add your email class as a service to be used as dependency injection in startup.cs?

This worked for me:

  1. Create the email settings which will be configured through appsettings.json
namespace ReservationBookingSystem.Model
{
    public class MailSettings
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public int Port { get; set; }
        public string FromEmail { get; set; }
        public string Host { get; set; }
    }
}
  1. create a mail interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ReservationBookingSystem.Model;

namespace ReservationBookingSystem.Services
{
    public interface IMailService
    {
        Task SendEmailAsync(string ToEmail, string Subject, string HTMLBody);
    }
}

  1. create MailService class
using ReservationBookingSystem.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;

namespace ReservationBookingSystem.Services
{
    public class MailService : IMailService
    {
        private readonly MailSettings _mailConfig;
        public MailService(MailSettings mailConfig)
        {
            _mailConfig = mailConfig;
        }

        public async Task SendEmailAsync(string ToEmail, string Subject, string HTMLBody)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            message.From = new MailAddress(_mailConfig.FromEmail);
            message.To.Add(new MailAddress(ToEmail));
            message.Subject = Subject;
            message.IsBodyHtml = true;
            message.Body = HTMLBody;
            smtp.Port = _mailConfig.Port;
            smtp.Host = _mailConfig.Host;
            smtp.EnableSsl = true;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(_mailConfig.Username, _mailConfig.Password);
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            await smtp.SendMailAsync(message);
        }
    }
}

  1. In Startup.cs add:
services.AddSingleton(Configuration.GetSection("MailSettings").Get<MailSettings>());
services.AddScoped<IMailService, MailService>();
  1. In appsettings.json add the mail configuration under 'MailSettings"
  2. In the razor component where you want to use it, just call the dependency injection. with @inject ReservationBookingSystem.Services.IMailService MailService. Inside the code call await MailService.SendEmailAsync("[email protected]", "test", "test");

This works in blazor server. So basically for you, replace MailSettings with CModule and you are good to go