[英]send email asp.net c#
是否可以使用 C# 中的 asp.net 項目從我的計算機(本地主機)發送 email? 最后我要將我的項目上傳到網絡服務器,但我想在上傳之前對其進行測試。
我找到了現成的源代碼並嘗試在 localhost 中運行它們,但它們都沒有成功運行。 例如這段代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
namespace sendEmail
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Btn_SendMail_Click(object sender, EventArgs e)
{
MailMessage mailObj = new MailMessage(
txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
SmtpClient SMTPServer = new SmtpClient("localhost");
try
{
SMTPServer.Send(mailObj);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
}
}
那么如何使用 asp.net C# 發送 email 呢? 我應該設置一些服務器配置嗎?
從Asp.Net發送電子郵件:
MailMessage objMail = new MailMessage("Sending From", "Sending To","Email Subject", "Email Body");
NetworkCredential objNC = new NetworkCredential("Sender Email","Sender Password");
SmtpClient objsmtp = new SmtpClient("smtp.live.com", 587); // for hotmail
objsmtp.EnableSsl = true;
objsmtp.Credentials = objNC;
objsmtp.Send(objMail);
如果你有一個Gmail帳戶,你可以使用谷歌smtp發送電子郵件
smtpClient.UseDefaultCredentials = false;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Credentials = new NetworkCredential(username,passwordd);
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
上面的代碼應該可以正常工作,但是您需要將以下內容添加到web.config中(作為任何基於代碼的SMTP配置的替代方法):
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="your.smtpserver.com" port="25" userName="smtpusername" password="smtppassword" />
</smtp>
</mailSettings>
</system.net>
如果您無法訪問遠程SMTP服務器(我使用自己的POP3 / SMTP電子郵件詳細信息),則可以在本地IIS實例中設置SMTP服務器,但是您可能會遇到中繼問題(因為大多數ISP)消費者IP地址黑名單)。
如果您無權訪問SMTP服務器,那么一個不錯的選擇是使用以下設置而不是上述設置:
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\mail"/>
</smtp>
</mailSettings>
</system.net>
這將創建電子郵件的硬盤副本,非常方便。 您需要創建上面指定的目錄,否則在嘗試發送電子郵件時會收到錯誤。
您可以在此處根據其他答案在代碼中配置這些詳細信息(通過在您創建的SmtpClient對象上配置屬性),但除非您從數據源獲取信息,或者信息是動態的,否則它是多余的編碼,當.Net已經為你做了這件事。
您可以通過System.Net.Mail
命名空間中的C#類庫從ASP.NET發送電子郵件。 看一下SmtpClient
類,它是發送電子郵件時涉及的主要類。
您可以在Scott Gu的博客或SmtpClient的MSDN頁面上找到代碼示例。
此外,您還需要運行SMTP服務器。 我可以建議使用針對開發的SMTP4Dev郵件服務器,不需要任何設置。
Create class name SMTP.cs then
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
/// <summary>
/// Summary description for SMTP
/// </summary>
public class SMTP
{
private SmtpClient smtp;
private static string _smtpIp;
public static string smtpIp
{
get
{
if (string.IsNullOrEmpty(_smtpIp))
_smtpIp = System.Configuration.ConfigurationManager.AppSettings["smtpIp"];
return _smtpIp;
}
}
public SMTP()
{
smtp = new SmtpClient(smtpIp);
}
public string Send(string From, string Alias, string To, string Subject, string Body, string Image)
{
try
{
MailMessage m = new MailMessage("\"" + Alias + "\" <" + From + ">", To);
m.Subject = Subject;
m.Priority = MailPriority.Normal;
AlternateView av1 = AlternateView.CreateAlternateViewFromString(Body, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html);
if (!string.IsNullOrEmpty(Image))
{
string path = HttpContext.Current.Server.MapPath(Image);
LinkedResource logo = new LinkedResource(path, MediaTypeNames.Image.Gif);
logo.ContentId = "Logo";
av1.LinkedResources.Add(logo);
}
m.AlternateViews.Add(av1);
m.IsBodyHtml = true;
smtp.Send(m);
}
catch (Exception e)
{
return e.Message;
}
return "sucsess";
}
}
then
on aspx page
protected void lblSubmit_Click(object sender, EventArgs e)
{
//HttpContext.Current.Response.ContentType = "text/plain";
//Guid guid = Guid.NewGuid();
string EmailMessage = "<html>" +
"<head>" +
"<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">" +
"</head>" +
"<body style=\"text-align:left;direction:ltr;font-family:Arial;\" >" +
"<style>a{color:#0375b7;} a:hover, a:active {color: #FF7B0C;}</style>" +
"<img src=\"" width=\"190px\" height= \"103px\"/><br/><br/>" +
"<p>Name: " + nameID.Value + ",<br/><br/>" +
"<p>Email: " + EmailID.Value + ",<br/><br/>" +
"<p>Comments: " + commentsID.Text + "<br/><br/>" +
// "Welcome to the Test local updates service!<br/>Before we can begin sending you updates, we need you to verify your address by clicking on the link below.<br/>" +
//"<a href=\""></a><br/><br/>" +
//"We look forward to keeping you informed of the latest and greatest events happening in your area.<br/>" +
//"If you have any questions, bug reports, ideas, or just want to talk, please contact us at <br/><br/>" +
//"Enjoy! <br/>" + commentsID.Text + "<br/>" +
//"Test<br/><a href=\"">www.Test.com</a></p>" +
"</body>" +
"</html>";
lblThank.Text = "Thank you for contact us.";
// string Body = commentsID.Text;
SMTP smtp = new SMTP();
string FromEmail = System.Configuration.ConfigurationManager.AppSettings["FromEmail"];
string mailReturn = smtp.Send(EmailID.Value, "", FromEmail, "Contact Us Email", EmailMessage, string.Empty);
//HttpContext.Current.Response.Write("true");
nameID.Value = "";
EmailID.Value = "";
commentsID.Text = "";
}
使用asp.net C#發送帶附件的電子郵件
public void Send(string from, string to, string Message, string subject, string host, int port, string password)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(from);
email.Subject = subject;
email.Body = Message;
SmtpClient smtp = new SmtpClient(host, port);
smtp.UseDefaultCredentials = false;
NetworkCredential nc = new NetworkCredential(txtFrom.Text.Trim(), password);
smtp.Credentials = nc;
smtp.EnableSsl = true;
email.IsBodyHtml = true;
email.To.Add(to);
string fileName = "";
if (FileUpload1.PostedFile != null)
{
HttpPostedFile attchment = FileUpload1.PostedFile;
int FileLength = attchment.ContentLength;
if (FileLength > 0)
{
fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Path.Combine(Server.MapPath("~/EmailAttachment"), fileName));
Attachment attachment = new Attachment(Path.Combine(Server.MapPath("~/EmailAttachment"), fileName));
email.Attachments.Add(attachment);
}
}
smtp.Send(email);
}
逐步完成教程(使用視頻)訪問http://dotnetawesome.blogspot.in/2013/09/send-email-with-attachment-using-cnet.html
如果您不想使用gmail或hotmail,以下是您的解決方案:
SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("info@MyWebsiteDomainName.com", "myIDPassword");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
//Setting From , To and CC
mail.From = new MailAddress("info@MyWebsiteDomainName", "MyWeb Site");
mail.To.Add(new MailAddress("info@MyWebsiteDomainName"));
mail.CC.Add(new MailAddress("MyEmailID@gmail.com"));
smtpClient.Send(mail);
希望它有幫助:)
Server.mappath不存在。 沒有Server對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.