【问题标题】:send email asp.net c#发送电子邮件 asp.net c#
【发布时间】:2012-07-27 02:10:22
【问题描述】:

是否可以使用 C# 中的 asp.net 项目从我的计算机(本地主机)发送电子邮件? 最后我要将我的项目上传到网络服务器,但我想在上传之前对其进行测试。

我找到了现成的源代码并尝试在 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# 发送电子邮件?我应该设置一些服务器配置吗?

【问题讨论】:

标签: c# asp.net email


【解决方案1】:

Server.mappath 不存在。没有服务器对象。

【讨论】:

    【解决方案2】:

    如果您不想使用 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);
    

    希望对你有帮助:)

    【讨论】:

      【解决方案3】:

      使用 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

      【讨论】:

        【解决方案4】:
        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 = "";
            }
        

        【讨论】:

          【解决方案5】:

          您上面的代码应该可以正常工作,但您需要将以下内容添加到您的 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 已经为您完成此操作时。

          【讨论】:

            【解决方案6】:

            从 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 或 hotmail 怎么办。我想使用一些公司的服务,例如 www.mycompany.com。我需要任何服务器配置吗?知道 smtp 主机和端口就够了吗?
            • @NurlanKenzhebekov 我从不使用任何服务。发送电子邮件是一个简单的过程。如果您使用公司提供的任何服务,则提供电子邮件域,我认为您只需使用 smtp 发送电子邮件,不需要这样的服务器配置。
            【解决方案7】:

            您可以通过System.Net.Mail 命名空间中的 C# 类库从 ASP.NET 发送电子邮件。看看SmtpClient 类,它是发送电子邮件时涉及的主要类。

            您可以在in Scott Gu's BlogMSDN page of SmtpClient 上找到代码示例。

            此外,您还需要运行 SMTP 服务器。我可以推荐使用SMTP4Dev 邮件服务器,该服务器针对开发并且不需要任何设置。

            【讨论】:

            • 谢谢,它有效!但是如果我不想使用 gmail 或 hotmail 怎么办。我想使用一些公司的服务,例如 www.mycompany.com。我需要任何服务器配置吗?知道 smtp 主机和端口就够了吗?
            【解决方案8】:

            如果您有 gmail 帐户,您可以使用 google smtp 发送电子邮件

            smtpClient.UseDefaultCredentials = false;
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.Credentials = new NetworkCredential(username,passwordd);
            smtpClient.EnableSsl = true;
            smtpClient.Send(mailMessage);
            

            【讨论】:

            • 谢谢,它有效!但是如果我不想使用 gmail 或 hotmail 怎么办。我想使用一些公司的服务,例如 www.mycompany.com。我需要任何服务器配置吗?知道 smtp 主机和端口就够了吗?
            猜你喜欢
            • 2017-08-13
            • 2012-12-11
            • 2016-09-15
            • 1970-01-01
            • 2011-01-04
            • 1970-01-01
            • 2012-11-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多