/// <summary>
/// 发送邮件
/// </summary>
/// <param name="strSmtpServer">smtp地址</param>
/// <param name="UserName">用户名</param>
/// <param name="Password">密码</param>
/// <param name="strFrom">发信人地址</param>
/// <param name="strto">收信人地址</param>
/// <param name="strSubject">邮件标题</param>
/// <param name="strBody">邮件正文</param>
public static void SendMail(string strSmtpServer, string UserName, string Password, string strFrom, string strto, string strSubject, string strBody, string strFileName)
{
//生成一个 使用SMTP发送邮件的客户端对象
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(strSmtpServer); //表示以当前登录用户的默认凭据进行身份验证
client.UseDefaultCredentials = true; //包含用户名和密码
client.Credentials = new System.Net.NetworkCredential(UserName, Password); //指定如何发送电子邮件。
//Network 电子邮件通过网络发送到 SMTP 服务器。
//PickupDirectoryFromIis 将电子邮件复制到挑选目录,然后通过本地 Internet 信息服务 (IIS) 传送。
//SpecifiedPickupDirectory 将电子邮件复制到 SmtpClient.PickupDirectoryLocation 属性指定的目录,然后由外部应用程序传送。 client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; //建立邮件对象
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(strFrom, strto, strSubject,strBody); //定义邮件正文,主题的编码方式
message.BodyEncoding = System.Text.Encoding.GetEncoding("gb2312");
message.SubjectEncoding = System.Text.Encoding.GetEncoding("gb2312");
//获取或设置一个值,该值指示电子邮件正文是否为 HTML。
message.IsBodyHtml = false;
//指定邮件优先级
message.Priority = System.Net.Mail.MailPriority.Normal; //添加附件
//System.Web.Mail.MailAttachment mailAttachment=new System.Web.Mail.MailAttachment(@"f:/baihe.txt");
if (strFileName != "" && strFileName != null)
{
Attachment data = new Attachment(strFileName);
message.Attachments.Add(data);
}
//发件人身份验证
client.Credentials = new System.Net.NetworkCredential(strFrom, Password);
//发送
client.Send(message);
} protected void Button1_Click(object sender, EventArgs e)
{
SendMail("smtp-ent.21cn.com", "zhouyf", "abc123", "[email protected]", TextBox1.Text.Trim(), TextBox2.Text.Trim(), TextBox3.Text.Trim(), TextBox4.Value.Trim());
//SendMail("smtp.163.com", "abc", "abc", "[email protected]", TextBox1.Text.Trim(), TextBox2.Text.Trim(), TextBox3.Text.Trim(), TextBox4.Value.Trim());
}
/// 发送邮件
/// </summary>
/// <param name="strSmtpServer">smtp地址</param>
/// <param name="UserName">用户名</param>
/// <param name="Password">密码</param>
/// <param name="strFrom">发信人地址</param>
/// <param name="strto">收信人地址</param>
/// <param name="strSubject">邮件标题</param>
/// <param name="strBody">邮件正文</param>
public static void SendMail(string strSmtpServer, string UserName, string Password, string strFrom, string strto, string strSubject, string strBody, string strFileName)
{
//生成一个 使用SMTP发送邮件的客户端对象
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(strSmtpServer); //表示以当前登录用户的默认凭据进行身份验证
client.UseDefaultCredentials = true; //包含用户名和密码
client.Credentials = new System.Net.NetworkCredential(UserName, Password); //指定如何发送电子邮件。
//Network 电子邮件通过网络发送到 SMTP 服务器。
//PickupDirectoryFromIis 将电子邮件复制到挑选目录,然后通过本地 Internet 信息服务 (IIS) 传送。
//SpecifiedPickupDirectory 将电子邮件复制到 SmtpClient.PickupDirectoryLocation 属性指定的目录,然后由外部应用程序传送。 client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; //建立邮件对象
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(strFrom, strto, strSubject,strBody); //定义邮件正文,主题的编码方式
message.BodyEncoding = System.Text.Encoding.GetEncoding("gb2312");
message.SubjectEncoding = System.Text.Encoding.GetEncoding("gb2312");
//获取或设置一个值,该值指示电子邮件正文是否为 HTML。
message.IsBodyHtml = false;
//指定邮件优先级
message.Priority = System.Net.Mail.MailPriority.Normal; //添加附件
//System.Web.Mail.MailAttachment mailAttachment=new System.Web.Mail.MailAttachment(@"f:/baihe.txt");
if (strFileName != "" && strFileName != null)
{
Attachment data = new Attachment(strFileName);
message.Attachments.Add(data);
}
//发件人身份验证
client.Credentials = new System.Net.NetworkCredential(strFrom, Password);
//发送
client.Send(message);
} protected void Button1_Click(object sender, EventArgs e)
{
SendMail("smtp-ent.21cn.com", "zhouyf", "abc123", "[email protected]", TextBox1.Text.Trim(), TextBox2.Text.Trim(), TextBox3.Text.Trim(), TextBox4.Value.Trim());
//SendMail("smtp.163.com", "abc", "abc", "[email protected]", TextBox1.Text.Trim(), TextBox2.Text.Trim(), TextBox3.Text.Trim(), TextBox4.Value.Trim());
}
解决方案 »
- 求一个思路,如果有例子更好!!没有例子,求高手给一个思路!!
- 求 js 代码
- 怎么对datalist 里面的控件进行动态的修改
- 请问如何把一个参数传向多个页面??
- ASP.NET中如何判断不同Session值显示不同的TreeView控件?
- 使用Application Center Test 却无法加载程序?
- 我想在aspx页面中引用一个activex控件,并执行它的方法,请问如何实现?这个activex是用delphi写的。
- 无法将文件“Yingnet.YingnetOA.DB.dll”复制到运行目录。----在线等,各位这是个什么问题啊
- 问一下 建程序时候的问题(图)
- 下载文件时遇到的问题。
- 请问那些控件是怎么工作的呢
- 第一列字段名,第二列输入框这样的模板列怎么做?
public static bool SendEmail(
string server, int port,
string user, string pass,
System.Net.Mail.MailMessage mail
)
{
System.Net.Mail.SmtpClient client = new SmtpClient(server, port);
client.Credentials = new System.Net.NetworkCredential(user, pass);
client.Send(mail);
return true;
}
--------------------------------------
smtp-ent.21cn.com
用户:[email protected]
密码:abc123
------------------------------
注:同样资料,在FOXMAIL里配置,也是可以发的.
client.EnableSsl = true;
来表示
gmail就是SSL的 所以必须启用SSl觉得代码中这个是多余的
//表示以当前登录用户的默认凭据进行身份验证
client.UseDefaultCredentials = true;因为你明确指定了一个Credential
麻烦大家用以下资料,在自己的邮件程序里试1下.
----真实资料-----------------------------------
smtp-ent.21cn.com
用户:[email protected]
密码:abc123
------------------------------
注:以上资料,在FOXMAIL里配置,是可以发的.
/* Project name: MailDaemon */
/* Module name: Mail Sender */
/* Author: Ming Yeh */
/* Created date: 2006-08-21 */
/* Last modified by: */
/* Last modify date: */
/* .-._ */
/* {_}^ )o */
/* {\________//~` */
/* ( ) */
/* /||~~~~~||\ */
/* |_\\_ \\_\_ */
/* */
/*****************************************/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Text;namespace mailDaemon
{
class MailSender
{
private const string SERVER_IP = "61.181.255.80";
private const string SENDER_EMAIL = "[email protected]";
private const string USERNAME = "mailist";
private const string PASSWORD = "bu2kwh1at";
private const string SUBJECT = "高速路商机速递";
string _server;
string _senderEmail;
string _username;
string _password;
static bool mailSent = false; public MailSender(string server, string senderEmail, string username, string password)
{
_server = server;
_senderEmail = senderEmail;
_username = username;
_password = password;
}
public MailSender():this(SERVER_IP, SENDER_EMAIL, USERNAME, PASSWORD)
{
}
public void SendMail(string email, string content)
{
MailMessage msg = new MailMessage(_senderEmail, email, SUBJECT, content);
msg.BodyEncoding = Encoding.UTF8;
msg.Priority = MailPriority.High;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient(_server);
NetworkCredential credential = new NetworkCredential(_username, _password);
client.UseDefaultCredentials = false;
client.Credentials = credential;
client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
client.SendAsync(msg, "Message Sent.");
Console.WriteLine(email + "邮件发送中,按C取消发送");
//string answer = Console.ReadLine();
//if (answer.StartsWith("c") && mailSent == false)
//{
// client.SendAsyncCancel();
//}
Console.WriteLine(email + "处理完成");
} void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
String token = (string)e.UserState; if (e.Cancelled)
{
Console.WriteLine("[{0}] Send canceled.", token);
}
if (e.Error != null)
{
Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
}
else
{
Console.WriteLine("Message sent.");
}
mailSent = true;
}
}
}
smtp-ent.21cn.com
用户:[email protected]
密码:abc123同样资料,FOXMAIL可以,我们程序不可以...--另外:如果是杀毒软件,不会有,163可以,21cn不可以的现象啊.
利用ASP.NET的组件发邮件(二)
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +1002034
System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +33
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +431[WebException: 无法连接到远程服务器]
System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) +1447624
System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) +190
System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +21
System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +318
System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) +227
System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) +316
System.Net.Mail.SmtpClient.GetConnection() +42
System.Net.Mail.SmtpClient.Send(MailMessage message) +1485[SmtpException: 发送邮件失败。]
System.Net.Mail.SmtpClient.Send(MailMessage message) +2074
MailSystem.CommonClass.SendMail(String strSmtpServer, String UserName, String Password, String strFrom, String strto, String strSubject, String strBody, String strFileName) in e:\项目\SendMail2005\App_Code\CommonClass.cs:98
Send.SendButton_Click(Object sender, EventArgs e) in e:\项目\SendMail2005\Send.aspx.cs:39
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint
.NET SMTP组件不直接支持
但可以通过CDO的方式
可以通过设置MaillMessage的Field 属性 来实现楼主google一下巴
// Constructor
private AlarmSendingByEmail(string occurredTime, AlarmTag alarmTag, List<string> emailList,
String language, int count)
{
this.occurredTime = occurredTime;
this.alarmTag = alarmTag;
this.emailList = emailList;
this.sendingMode = Common.SendingMode.EMAIL.ToString();
this.language = language;
this.count = count; DataFactory temp = new DataFactory("AlarmSystem");
DataTable smtpTable = temp.GetTable("Select smtp, sender, subject, Account, AccountPassword from TMailAccount"); if (smtpTable.Rows.Count != 1)
{
LogEntry log = new LogEntry();
log.Message = "Record of TMailAccount is wrong!";
Dictionary<string, object> errorInfo = new Dictionary<string, object>();
errorInfo.Add("DateTime", DateTime.Now);
log.ExtendedProperties = errorInfo;
log.Categories.Add("Error");
Logger.Write(log);
return;
} this.mailHost = smtpTable.Rows[0]["Smtp"].ToString();
this.sender = smtpTable.Rows[0]["Sender"].ToString();
this.mailSubject = smtpTable.Rows[0]["Subject"].ToString();
this.accountPWD = smtpTable.Rows[0]["AccountPassword"].ToString();
this.mailAccount = smtpTable.Rows[0]["Account"].ToString();
this.smtp = new SmtpClient(this.mailHost);
//如果Smtp服务器需要帐号、密码验证,并且数据库中有准确的帐户、密码
//用此帐户、密码进行验证
if ((mailAccount != "") && (accountPWD != ""))
{
this.smtp.Credentials = new System.Net.NetworkCredential(mailAccount, accountPWD);
}
} public static AlarmSendingByEmail GetInstance(string occurredTime, AlarmTag alarmTag, List<string> emailList,
String language, int count)
{
if (instance == null)
{
lock (lockObject)
{
if (instance == null)
{
instance = new AlarmSendingByEmail(occurredTime, alarmTag, emailList, language, count);
}
}
}
return instance;
} /// <summary>
/// 发送email,包含多个发送目标或多次发送。
/// </summary>
public override void Send()
{
lock (lockObject)
{
string message;
if (this.language == Common.SendingLanguage.CHS.ToString())
{
message = this.alarmTag.GetMessage(this.occurredTime, Common.SendingLanguage.CHS);
}
else //CHT
{
message = this.alarmTag.GetMessage(this.occurredTime, Common.SendingLanguage.CHT);
}
foreach (string address in this.emailList)
{
//发送Email方法
this.SendByEmail(address, this.count, message);
}
}
} //By navy
/// <summary>
/// 异步发送Email方法
/// </summary>
/// <param name="mailTo">Email要发送的地址</param>
/// <param name="sendCount">发送次数</param>
/// <param name="sendMessage">发送信息</param>
/// <returns></returns>
private void SendByEmail(string mailTo, int sendCount, string sendMessage)
{
for (int i = 0; i < sendCount; i++)
{
try
{
MailMessage mailMsg = new MailMessage(this.sender, mailTo, this.mailSubject, sendMessage);
object token = mailMsg;
this.smtp.SendAsync(mailMsg, token);
}
catch (SmtpException se)
{
//记录日志,记录信息包含失败原因,发送对象邮件地址
LogEntry log = new LogEntry();
log.Message = se.Message;
Dictionary<string, object> errorInfo = new Dictionary<string, object>();
errorInfo.Add("DateTime", DateTime.Now);
errorInfo.Add("Mail To: ", mailTo);
errorInfo.Add("Message: ", sendMessage);
errorInfo.Add("StackTrace: ", se.StackTrace);
log.ExtendedProperties = errorInfo;
log.Categories.Add("Error");
Logger.Write(log);
return;
}
}
}