ارسال ایمیل در ASP.NET Core
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۹/۱۰ ۱۲:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
{
"dependencies": {
"MailKit": "1.10.0"
}
} using System.Threading.Tasks;
using ASPNETCoreIdentitySample.Services.Contracts.Identity;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
namespace ASPNETCoreIdentitySample.Services.Identity
{
public class AuthMessageSender : IEmailSender, ISmsSender
{
public async Task SendEmailAsync(string email, string subject, string message)
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("DNT", "do-not-reply@dotnettips.info"));
emailMessage.To.Add(new MailboxAddress("", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart(TextFormat.Html)
{
Text = message
};
using (var client = new SmtpClient())
{
client.LocalDomain = "dotnettips.info";
await client.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false);
await client.SendAsync(emailMessage).ConfigureAwait(false);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
public Task SendSmsAsync(string number, string message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
} using (var stream = new FileStream($@"c:\smtppickup\email-{Guid.NewGuid().ToString("N")}.eml", FileMode.CreateNew))
{
emailMessage.WriteTo(stream);
} [System.Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")]
public class SmtpClient : IDisposable var smtp = new SmtpClient {
Host = StaticValues.HostEmail,
Port = StaticValues.PortEmail,
EnableSsl = false, //StaticValues.SslEmail,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromEmail, EmailPassword)
};
using(var message = new MailMessage(fromEmail, toEmail, subject, body) {
BodyEncoding = Encoding.UTF8,
IsBodyHtml = true,
HeadersEncoding = Encoding.UTF8,
DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
}) {
smtp.Send(message);
} PM> Install-Package DNTCommon.Web.Core
public class DiskSmtpClient : SmtpClient
{
public DiskSmtpClient(IOptionsSnapshot<MailKitOptions> mailOptionsSnapshot)
{
if (mailOptionsSnapshot.Value.SpecifiedPickupDirectory)
{
SpecifiedPickupDirectory = true;
PickupDirectoryLocation = mailOptionsSnapshot.Value.PickupDirectoryLocation;
}
}
public bool SpecifiedPickupDirectory { get; set; }
public string PickupDirectoryLocation { get; set; }
public override Task SendAsync(MimeMessage message, CancellationToken cancellationToken = new CancellationToken(),
ITransferProgress progress = null)
{
if (!SpecifiedPickupDirectory)
return base.SendAsync(message, cancellationToken, progress);
return SaveToPickupDirectory(message, PickupDirectoryLocation);
}
private async Task SaveToPickupDirectory(MimeMessage message, string pickupDirectory)
{
using (var stream = new FileStream($@"{pickupDirectory}\email-{Guid.NewGuid().ToString("N")}.eml", FileMode.CreateNew))
{
await message.WriteToAsync(stream);
}
}
public override Task ConnectAsync(string host, int port = 0, SecureSocketOptions options = SecureSocketOptions.Auto,
CancellationToken cancellationToken = new CancellationToken())
{
if (!SpecifiedPickupDirectory)
return base.ConnectAsync(host, port, options, cancellationToken);
return Task.CompletedTask;
}
public override Task DisconnectAsync(bool quit, CancellationToken cancellationToken = new CancellationToken())
{
if (!SpecifiedPickupDirectory)
return base.DisconnectAsync(quit, cancellationToken);
return Task.CompletedTask;
}
} services.AddTransient<DiskSmtpClient>();
var email = "mail@dotnettips.info";
var subject = "subject";
var message = "message";
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("DNT", "do-not-reply@dotnettips.info"));
emailMessage.To.Add(new MailboxAddress("", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart(TextFormat.Html)
{
Text = message
};
_client.SpecifiedPickupDirectory = true;
_client.PickupDirectoryLocation = "c:\\mail";
_client.LocalDomain = "dotnettips.info";
await _client.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false);
await _client.SendAsync(emailMessage).ConfigureAwait(false);
await _client.DisconnectAsync(true).ConfigureAwait(false); services.Configure<MailKitOptions>(options => Configuration.GetSection("MailKitOptions").Bind(options)); "MailKitOptions": {
"SpecifiedPickupDirectory": true,
"PickupDirectoryLocation": "c:\\mail"
} public class MailKitOptions
{
public bool SpecifiedPickupDirectory { get; set; }
public string PickupDirectoryLocation { get; set; }
} An unhandled exception has occurred while executing the request. MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection. The host name did not match the name given in the server's SSL certificate.
using (var client = new SmtpClient ()) {
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
client.CheckCertificateRevocation = false;
// ...
}
این نوع خطاها را اگر مشاهده کردید، مشکل از برنامه یا کتابخانهی خاصی نیست. مشکلات شبکهی داخلی هست.
+ پارامتر shouldValidateServerCertificate اضافه شد.