web-dev-qa-db-ja.com

.NET Core 2.2でメールを送信する

MVC ASP.NETでは、次のようにweb.configファイルでsmtp構成を設定できます。

<system.net>
    <mailSettings>
        <smtp from="MyEmailAddress" deliveryMethod="Network">
            <network Host="smtp.MyHost.com" port="25" />
        </smtp>
    </mailSettings>
</system.net>

そして、これは完璧に機能します。

しかし、appsettings.jsonファイルがあるため、.NET Core 2.2で動作させることができません。

私はこれを持っています:

"Smtp": {
    "Server": "smtp.MyHost.com",
    "Port": 25,
    "FromAddress": "MyEmailAddress"
}

メールを送信すると、次のエラーメッセージが表示されます。

enter image description here

3
user7849697

電子メールの送信者でOptionsをDIとともに使用できます。参照

https://kenhaggerty.com/articles/article/aspnet-core-22-smtp-emailsender-implementation

1.appsettings.json

"Smtp": {
    "Server": "smtp.MyHost.com",
    "Port": 25,
    "FromAddress": "MyEmailAddress"
}

2.SmtpSettings.cs

public class SmtpSettings
{
    public string Server { get; set; }
    public int Port { get; set; }
    public string FromAddress { get; set; }
}

3.スタートアップConfigureServices

public class Startup
{
    IConfiguration Configuration;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {

        services.Configure<SmtpSettings>(Configuration.GetSection("Smtp"));
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();
    }
}

4. Optionsを使用して、必要に応じてDIでSmtpSettingsにアクセスします。

public class EmailSender : IEmailSender
{
    private readonly SmtpSettings _smtpSettings;

    public EmailSender(IOptions<SmtpSettings> smtpSettings)
    {
        _smtpSettings = smtpSettings.Value;

    }
    public Task SendEmailAsync(string email, string subject, string message)
    {
        var from = _smtpSettings.FromAddress;
        //other logic
        using (var client = new SmtpClient())
        {
            {
                await client.ConnectAsync(smtpSettings.Server, smtpSettings.Port, true);
            }
        }
        return Task.CompletedTask;
    }
}
1
Xing Zou

Appsettings.jsonからSMTP設定を取得するには、次の手順に従います。

  1. appsettings.json値、
   "EmailSettings": {
    "EmailSettings": {
    "MailServer": "smtp.gmail.com",
    "MailPort": 587,
    "SenderName": "Sender Name",
    "SenderEmail": "preferred email",
    "UserName": "username",
    "Password": "password",
    "EnableSsl": "true", /// if you need it use
    "EmailKey": "EmailKey" /// if you need it use
  }
  1. メール認証情報のプロパティを定義します。

    public void ConfigureServices(IServiceCollection services)
    {
      services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
    }
    

3.クラスのプロパティ、

    public class EmailSettings
    {
        public string MailServer { get; set; }
        public int MailPort { get; set; }
        public string SenderName { get; set; }
        public string SenderEmail { get; set; }
        public string Password { get; set; }
        public bool EnableSsl { get; set; }
        public string EmailKey { get; set; }
    }
  1. 発信者、
var emailResult = SendEmail(loginName, Message, subject, "User Creation");

5.値を取得して設定し、

        public async Task<IActionResult> SendEmail(string email, string Message, string Subject, string EmailType, string HTMLMessageContent = "")
        {
            HTMLMessageContent = Message;
            EmailLog emailModel = new EmailLog
            {
                EmailType = EmailType,
                Subject = Subject,
                EmailContent = Message,
                FromEmail = _emailSettings.SenderEmail,
                ToEmails = email,
                CreatedBy = sessionData != null ? sessionData.ApplicationUserId : "",
                OrganizationId = sessionData != null ? sessionData.OrganizationId : 0

            };

           var from = new EmailAddress(_emailSettings.SenderEmail, _emailSettings.SenderName);
            var to = new EmailAddress(email, "");
            var msg = MailHelper.CreateSingleEmail(from, to, Subject, Message, HTMLMessageContent);
            var response = await client.SendEmailAsync(msg); 
            return Ok("Success");
        }

最後に、メールは関係者に送信されます。クールなコード.

0
Prakash CS