欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中发送邮件代码

程序员文章站 2024-02-03 08:04:28
始找的代码只能发送无smtp验证的邮件,但现在很多email发送时都需要验证,后来查找了下msdn的帮助,找到了发送验证的代码,贴出来希望对大家有所帮助! 复制代码 代码如...
始找的代码只能发送无smtp验证的邮件,但现在很多email发送时都需要验证,后来查找了下msdn的帮助,找到了发送验证的代码,贴出来希望对大家有所帮助!
复制代码 代码如下:

public static int sendmail(string to, string body,string subject)
    {
        try
        {
            int ncontain = 0;
            ///添加发件人地址
            string from = "你的发送email";
            mailmessage mailmsg = new mailmessage();
            mailmsg.from = new mailaddress(from);
            ncontain += mailmsg.from.address.length;
            ///添加收件人地址
            mailmsg.to.add(to);
            ncontain += mailmsg.to.tostring().length;
            ///添加邮件主题
            mailmsg.subject = subject;
            mailmsg.subjectencoding = encoding.utf8;
            ncontain += mailmsg.subject.length;
            ///添加邮件内容
            mailmsg.body = body;
            mailmsg.bodyencoding = encoding.utf8;
            mailmsg.isbodyhtml = true;
            ncontain += mailmsg.body.length;
            if (mailmsg.isbodyhtml == true)
            {
                ncontain += 100;
            }
            ///发送邮件
            try
            {
                //定义发送邮件的client
                smtpclient client = new smtpclient();
                //表示以当前登录用户的默认凭据进行身份验证 
                client.usedefaultcredentials = true;
                //包含用户名和密码 
                client.credentials = new system.net.networkcredential(application.getapplicationsendmail(), application.getapplicationsendpass());
                ///设置邮件服务器主机的ip地址
                client.host = "smtp服务器ip"
                ///设置邮件服务器的端口
                client.port = 25;
                ///配置发送邮件的属性
                client.deliverymethod = smtpdeliverymethod.network;
                //system.net.mail.mailmessage message = new system.net.mail.mailmessage(strfrom, strto, strsubject, strbody); 
                mailmsg.priority = system.net.mail.mailpriority.normal;
                //client.usedefaultcredentials = false;
                ///发送邮件
                client.send(mailmsg);
                return 1;
            }
            catch (exception ex) { return 0; }
        }
        catch (exception ex) { return 0; }
    }