7. How to send emails to dotnet core, 7. dotnetcore
Required Nuget package
"MailKit": "1.8.1 ",
Method
/// <Summary> /// send an email (Html and an attachment can be added) /// </summary> /// <param name = "subject"> email title </param> /// <param name = "email"> recipient address </param> /// <param name = "content"> email content </param> /// <param name = "filepath"> file relative path </param> public static void sendEmail (string subject, string email, string content, string filepath = null) {var message = new MimeMessage (); // sender message. from. add (new MailboxAddress ("sender name", "sender Email "); // recipient message. to. add (new MailboxAddress ("", email); // The title message. subject = subject; // generate a TextPart var body that supports Html = new TextPart (TextFormat. html) {Text = content}; // first generate a var multipart = new Multipart ("mixed"); // Add the body content multipart. add (body); if (! String. isNullOrWhiteSpace (filepath) {// generate an absolute Path // filepath = "Upload // NewsPhoto // readme.txt"; var absolutePath = Path. combine (_ hostingEnv. webRootPath, string. format (filepath); // attachment var attachment = new MimePart () {// read the File (only the absolute path can be used) ContentObject = new ContentObject (File. openRead (absolutePath), ContentEncoding. default), ContentDisposition = new ContentDisposition (ContentDisposition. attachment), ContentTransferEncoding = ContentEncoding. base64, // file name FileName = Path. getFileName (absolutePath)}; // Add the attachment multipart. add (attachment);} // body content message. body = multipart; using (var client = new SmtpClient () {// connect to the Smtp server client. connect ("smtp server address", port, false); // log on to the client. authenticate ("Account", "password"); // send client. send (message); // disconnect the client. disconnect (true );}}
The above method can send Html text with attachments