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; }
}
复制代码 代码如下:
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; }
}
上一篇: 吃掉网易,阿里打的一手好算盘
下一篇: 正则表达式的使用