ASP.NET Core 1.0实现邮件发送功能
程序员文章站
2023-12-10 22:36:34
准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供smtp相关类库,于是网上一搜发现了m...
准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供smtp相关类库,于是网上一搜发现了mailkit
好东西一定要试一下,何况是开源,下面是代码可实现smtp邮件发送:
using mailkit.net.smtp; using mailkit.security; using mimekit; using system.threading.tasks; namespace consoleapp1 { public class mailhelper { public static void send(string email, string subject, string message) { var emailmessage = new mimemessage(); emailmessage.from.add(new mailboxaddress("tianwei blogs", "mail@hantianwei.cn")); emailmessage.to.add(new mailboxaddress("mail", email)); emailmessage.subject = subject; emailmessage.body = new textpart("plain") { text = message }; using (var client = new smtpclient()) { client.connect("smtp.hantianwei.cn", 465, true); client.authenticate("mail@hantianwei.cn", "******"); client.send(emailmessage); client.disconnect(true); } } public static async task sendemailasync(string email, string subject, string message) { var emailmessage = new mimemessage(); emailmessage.from.add(new mailboxaddress("tianwei blogs", "mail@hantianwei.cn")); emailmessage.to.add(new mailboxaddress("mail", email)); emailmessage.subject = subject; emailmessage.body = new textpart("plain") { text = message }; using (var client = new smtpclient()) { await client.connectasync("smtp.hantianwei.cn", 25, securesocketoptions.none).configureawait(false); await client.authenticateasync("mail@hantianwei.cn", "******"); await client.sendasync(emailmessage).configureawait(false); await client.disconnectasync(true).configureawait(false); } } } }
以上代码同步异步都没有问题
注:一般邮箱如腾讯企业邮、163等都可以发送成功,但阿里云邮件推送失败,如果有高手可实现阿里云推送邮件请告诉我一下,非常感谢!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。