C#发送邮件(包含发送附件)

如何搞到SMTP服务器地址百度即可,参考链接:阿里云SMTP服务器地址

Console.WriteLine("如果发现有错误的地方,麻烦同学私信我或评论我一下,我好加以改正");
Console.WriteLine("如果有看不懂的同学,可以私信我,存有案例,更方便分析(9:30-17:00在线)");

以下代码为了更能体现开发情况所写,如果只需要方法的话,可以参考更为简便的代码:C#发送邮件方法

//邮箱、SMTP服务器地址、SMTP端口号、授权码 可以在配置文件中配置,以便统一进行修改

<configuration>
	<appSettings>
		
		
		<add key="Email_Sender" value="[email protected]" />
		
		<add key="Email_SMTP" value="smtp.qq.com" />//qqSMTP服务器地址
		
		<add key="Email_Port" value="587" />//qqSMTP端口号
		
		<add key="Email_Code" value="xxxxxxxxxxxx" />//qqSMTP授权码
	appSettings>
configuration>
namespace TestConsole
{
    class Program
    {
		private String emailSender = ConfigurationManager.AppSettings["Email_Sender"];//发送邮箱
		private String emailSMTP = ConfigurationManager.AppSettings["Email_SMTP"];//服务器地址
		private String emailPort = ConfigurationManager.AppSettings["Email_Port"];//端口号
		private String emailCode = ConfigurationManager.AppSettings["Email_Code"];//授权码
		
    	public static void Main(String[] args)
		{
			String email = "[email protected]";//接收邮箱
			String[] emailtocc = new String[]{"[email protected]", "[email protected]"};//抄送邮箱
			SendEmail("", new String[]{}, "fromnName", "《这是发送邮件的标题》", "这是邮件的主体内容(支持html格式)!!!");
		}
		
		/// 
		/// 发送邮件
		/// 
		/// 收件人地址
		/// 抄送人地址(多人)
		/// 发件人名称
		/// 邮件标题
		/// 邮件内容(支持html格式)
		public static void SendEmail(String sendTo, String[] sendCC, String fromName, String title, String body)
		{
			MailMessage msg = new MailMessage();
		
			//设置收件人地址
			msg.To.Add(sendTo); //收件人地址
		
			//设置抄送人地址
			if (sendCC.Length > 0)
			{
				foreach (String cc in sendCC)
				{
					msg.CC.Add(cc);
				}
			}
		
			//设置发件人邮箱及名称
			msg.From = new MailAddress(emailSender, fromName);
		
			msg.Subject = title;//邮件标题 
			msg.SubjectEncoding = Encoding.UTF8; //标题格式为UTF8 
		
			msg.Body = body;//邮件内容
			msg.BodyEncoding = Encoding.UTF8; //内容格式为UTF8 
			msg.IsBodyHtml = true;//设置邮件格式为html格式

			string filePath = @"E:\导出数据.xls";//添加附件
			msg.Attachments.Add(new Attachment(filePath));
		
			SmtpClient client = new SmtpClient();
		
			//发送邮箱信息
			client.Host = emailSMTP; //SMTP服务器地址 
			client.Port = emailPort; //SMTP端口,QQ邮箱填写587 
		
			client.EnableSsl = true; //启用SSL加密 (使用除QQ邮箱之外的最好关闭)
		
			//发件人邮箱账号,授权码
			client.Credentials = new System.Net.NetworkCredential(emailSender, emailCode);
		
			try
			{
				client.Send(msg); //发送邮件
			}
			catch (Exception)
			{
				throw;
			}
		}
    }
}

你可能感兴趣的:(C#,c#,服务器,开发语言)