C# 发送邮件(带有附件)
当前所用框架(.NET 5.0),这里使用QQ邮箱作为示例
一、开通 POP3/SMTP服务 (如何使用 Foxmail 等软件收发邮件?)、并记录授权密钥
![](https://img2023.cnblogs.com/blog/1867856/202212/1867856-20221206100912456-2032282430.png)
二、引用Nuget包:MailKit(3.2.0)、MimeKit(3.2.0)
using MailKit.Security; using MimeKit; using System; using System.Net.Mime; namespace Mailbox { internal class Program { static void Main(string[] args) { QQEmail email = new QQEmail(); email.AddFile(@"F:\Kyson\其他文件\Mailbox\Mailbox\images\1.jpg", "1.jpg"); string html = "<p>我是邮件文字/html内容</p>"; email.Send("主题:测试发送邮件", "xxxx@qq.com", "xxxx@qq.com", html); } } public class QQEmail { Multipart multipart = new Multipart("mixed"); /// <summary> /// 添加文件 /// </summary> /// <param name="file"></param> /// <param name="name"></param> public bool AddFile(string file, string name) { if (!System.IO.File.Exists(file)) { return false; } try { System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); //附件 var attimg = new MimePart(MediaTypeNames.Application.Octet) { Content = new MimeContent(fs, ContentEncoding.Default), ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Default, FileName = name, IsAttachment = true, }; multipart.Add(attimg); return true; } catch (Exception ex) { return false; } } /// <summary> /// 发送 /// </summary> /// <param name="subject">主题</param> /// <param name="from">发送人</param> /// <param name="to">接收人</param> /// <param name="html">邮件内容支持html</param> /// <returns></returns> public string Send(string subject, string from, string to, string html) { using (var smtp = new MailKit.Net.Smtp.SmtpClient()) { MimeMessage mail = new MimeMessage(); mail.From.Add(new MailboxAddress("Yuan天空", from)); mail.To.Add(new MailboxAddress(to, to)); mail.Subject = subject; if (string.IsNullOrEmpty(html)) { return "发送内容不能为空"; } var Html = new TextPart(MimeKit.Text.TextFormat.Html) { Text = html }; multipart.Add(Html); mail.Body = multipart; smtp.ServerCertificateValidationCallback = (s, c, h, e) => true; //连接邮箱服务器 //!!!需要注意的是阿里云服务器默认是禁止25端口的,安全组添加也不行需要提交阿里云审核才能开通 , 这里使用587端口是可以发送的(服务器实测发送延迟很高 ,本地调试发送挺快, 不知道是不是服务器配置比较低的原因) smtp.Connect("smtp.qq.com", 587, SecureSocketOptions.None); //登录认证 qq邮箱账号和授权密钥 smtp.Authenticate("xxxx@qq.com", "xxxx"); smtp.Timeout = 600000; string res = smtp.Send(mail); smtp.Disconnect(true); return res; } } } }
三、效果展示