C# 发送邮件功能

前言:
SMTP(Simple Mail Transport Protocol)简单邮件传输协议。在.NET Frameword类库中提供SmtpClient类(System.Net.Mail),她提供了一个轻型方法来发送SMTP电子邮件信息。SmtpClient类中的Bcc属性是用来指定此电子邮件抄送的收件人的集合,这就意味着可以为每个邮件制定多个收件地址。Attachmenty属性也是一个集合,可以使用它为邮件添加多个附件。 发送邮件中用的其他类主要还有

1.Attachment类,表示文件附件,它允许将文本、流、文件附加到电子邮件中。

2.MailAddress类,表示邮件地址。

3.MailMessage类,表示电子邮件

SmtpClient mailClient = new SmtpClient("smtp.qq.com");
//Credentials登陆SMTP服务器的身份验证. (这里的用户名是完整的邮箱账号,密码就是SMTP的密码)
mailClient.Credentials = new NetworkCredential("用户名", "密码");
//[email protected]发件人地址、[email protected]收件人地址
MailMessage message = new MailMessage(new MailAddress("[email protected]"),new MailAddress([email protected]));
// message.Bcc.Add(new MailAddress("[email protected]")); //可以添加多个收件人
message.Body = "Hello Word!";//邮件内容
message.Subject = "this is a test";//邮件主题
//Attachment 附件
Attachment att = new Attachment(@"C:"hello.txt");
message.Attachments.Add(att);//添加附件
Console.WriteLine("Start Send Mail....");
//发送....
mailClient.Send(message);
Console.WriteLine("Send Mail Successed");
Console.ReadLine();

--------------------------------------------------------------GMAIL---------------------------------------------------
private void button1_Click(object sender, EventArgs e)
{
string MyPsd = G_password.Text;
string MyEmail = G_email.Text.Trim() + "@gmail.com";
MailMessage MMsg = new MailMessage();
MMsg.Subject = G_subject.Text.Trim();
MMsg.From = new MailAddress(MyEmail);
MMsg.To.Add(new MailAddress(G_address.Text.Trim()));
MMsg.IsBodyHtml = true;//这里启用IsBodyHtml是为了支持内容中的Html。
MMsg.BodyEncoding = Encoding.UTF8;//将正文的编码形式设置为UTF8。
MMsg.Body = G_content.Text;
SmtpClient SClient = new SmtpClient();
SClient.Host = "smtp.gmail.com";//google的smtp地址
SClient.Port = 587;//google的smtp端口
SClient.EnableSsl = true;//因为google使用了SSL(安全套接字层)加密链接所以这里的EnableSsl必须设置为true。
SClient.Credentials = new NetworkCredential(MyEmail, MyPsd);
if (G_Attachment.Text.Length>0)
{
MMsg.Attachments.Add(new Attachment(G_Attachment.Text));//判断是否有附件
}
try
{
SClient.Send(MMsg);
MessageBox.Show("邮件已经发送成功");
}
catch (Exception err)
{

            MessageBox.Show(err.Message, "错误提示");
        }



    }

你可能感兴趣的:(C# 发送邮件功能)