C# 发送邮件

来源:互联网 发布:qq飞车暗夜王爵数据 编辑:程序博客网 时间:2024/05/29 14:31
主要控件属性

    型                                      述                                Name属性                                   

TextBox                                收件人地址                          txtAddress

TextBox                                标题                                      txtTitle

TextBox                                内容                                     txtContent                               Mutiline属性为True

TextBox                                附件                                     txtAttachment                         ReadOnly属性为True

Button                                  发送                                      btSend

Button                                  添加附件                               btAddAttachment

双击“发送”按钮,打开代码视图,在代码窗口的顶部添加对命名空间的引用,代码如下:

using System.Net.Mail;

在“发送”按钮的Click事件中,添加对SendMail函数的调用,代码如下:

private void btSend_Click(object sender, EventArgs e)

{

    if (SendMail())

    {

        MessageBox.Show("发送成功");

    }

}

编写SendMail函数,代码如下:

//发送电子邮件成功返回True,失败返回False

private bool SendMail()

{

    MailAddress from = new MailAddress("FromMailBox@Sina.com ", "测试账号");//在此处填入发送邮件的邮箱

    //收件人地址

    MailAddress to = new MailAddress(this.txtAddress.Text, "hello");

    MailMessage message = new MailMessage(from, to);

    //添加附件,判断文件存在就添加

    if(System.IO.File.Exists(this.txtAttachment.Text))

    {

      Attachment item =new Attachment(this.txtAttachment.Text, MediaTypeNames.Text.Plain);

        message.Attachments.Add(item);

    }

    message.Subject = this.txtTitle.Text; // 设置邮件的标题

    message.Body = this.txtContent.Text; //发送邮件的正文

    message.BodyEncoding = System.Text.Encoding.Default;

   MailAddress other = new MailAddress("otherPerson@163.com");

    message.CC.Add(other); //添加抄送人

    //创建一个SmtpClient 类的新实例,并初始化实例的SMTP 事务的服务器

    SmtpClient client = new SmtpClient(@"smtp.Sina.com");//SmtpClient client = new SmtpClient(@"smtp.qq.com");

    client.DeliveryMethod = SmtpDeliveryMethod.Network;

    client.UseDefaultCredentials = false;

    client.EnableSsl = false;

    //身份认证

    client.Credentials = new System.Net.NetworkCredential("FromMailBox@Sina.com", "*****");//发送邮件的邮箱以及邮箱密码

    bool ret =true; //返回值

    try

   {

        client.Send(message);

     }

    catch (SmtpException ex)

    {

        MessageBox.Show(ex.Message);

        ret =false;

    }

    catch(Exception ex2)

    {

        MessageBox.Show(ex2.Message);

        ret = false;

    }

    return ret;

}

按F5键运行程序,测试邮件的发送功能。

技巧:为了简化程序,上列中用于发送邮件的地址HardCode(硬代码)了,读者可以增加输入框来录入发送地址、密码和SMTP服务器等信息,让程序变得更灵活。

本章主要介绍了如何使用System.Net.Mail命名空间下的类。其中,SmtpClient类可以发送电子邮件,MailMessage类可以丰富电子邮件的内容,MailAddress类可以设置电子邮件的收件人或发件人的电子邮件地址,Attachment类可以为邮件添加附件。

通过对本章的学习,读者可以掌握发送电子邮件的技巧,还能为应用程序提供自动发送电子邮件的功能。

 

其中SMTP的设置,我测试的时候用的qq邮箱发送邮件给qq邮箱,那么发送邮件的邮箱就需要开启QQ邮箱的IMAP/SMTP服务,也就是进入邮箱首页-->设置-->账户-->选择SMTP服务

原创粉丝点击