Hi @,
and it has to be by using "TryAddTransient". Any solutions for that?
It looks like you want to create and manage your service for sending emails or SMS. In this case, you can refer to the following simple example (send email):
IEmailService.cs
public interface IEmailService
{
Task SendEmailAsync(string to, string subject, string body);
}
public class EmailService : IEmailService
{
private readonly SmtpClient _smtpClient;
private readonly string _fromEmail;
public EmailService(string smtpHost, int smtpPort, string fromEmail, string fromPassword)
{
_smtpClient = new SmtpClient(smtpHost, smtpPort)
{
Credentials = new NetworkCredential(fromEmail, fromPassword),
EnableSsl = true
};
_fromEmail = fromEmail;
}
public async Task SendEmailAsync(string to, string subject, string body)
{
var mailMessage = new MailMessage(_fromEmail, to)
{
Subject = subject,
Body = body,
IsBodyHtml = true
};
await _smtpClient.SendMailAsync(mailMessage);
Console.WriteLine($"Email sent to {to}: {subject}");
}
}
Test with gmail below:
static async Task Main(string[] args)
{
// Configuring Dependency Injection
var services = new ServiceCollection();
// Register for email service
services.TryAddTransient<IEmailService>(provider =>
{
// Configuring SMTP Server Information
string smtpHost = "smtp.gmail.com"; // SMTP server address
int smtpPort = 587; // SMTP port
string fromEmail = "******@gmail.com"; // sender email
string fromPassword = "your app password";
return new EmailService(smtpHost, smtpPort, fromEmail,fromPassword);
});
var serviceProvider = services.BuildServiceProvider();
// Parsing mail service
var emailService = serviceProvider.GetRequiredService<IEmailService>();
// send email
string to = "recipient@example.com"; // Recipient's email
string subject = "Test Email";
string body = "<h1>Hello, this is a test email!</h1>";
try
{
await emailService.SendEmailAsync(to, subject, body);
Console.WriteLine("Email sent successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to send email: {ex.Message}");
}
}
Best regards,
Xudong Peng
If the answer is the right solution, please click "Accept Answer" and kindly upvote. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.