如何在ASP.NET C#中发送电子邮件


91

我是ASP.NET C#领域的新手。我打算通过ASP.NET C#发送邮件,这是我的ISPSMTP地址:

smtp-proxy.tm.net.my

以下是我尝试执行的操作,但失败了。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SendMail" %>
<html>
<head id="Head1" runat="server"><title>Email Test Page</title></head>
<body>
    <form id="form1" runat="server">
        Message to: <asp:TextBox ID="txtTo" runat="server" /><br>
        Message from: <asp:TextBox ID="txtFrom" runat="server" /><br>
        Subject: <asp:TextBox ID="txtSubject" runat="server" /><br>
        Message Body:<br>
        <asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine"  Width="270px" /><br>
        <asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email" /><br>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>

下面是我的代码背后

using System;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
    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("127.0.0.1");
        try
        {
            SMTPServer.Send(mailObj);
        }
        catch (Exception ex)
        {
            Label1.Text = ex.ToString();
        }
    }
}

PS:对不起,我无法理解接收方/发送方SMTP的概念,因此,我试图从此处理解整个概念。


当您单击按钮时,它是否到达了后面的代码?
康拉德·洛兹

您是否在localhost上的IIS中设置了smtp?什么是失败的?您在ISP上有一个邮件帐户吗?
mrtig

Answers:


115

只需通过下面的代码。

SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);

smtpClient.Credentials = new System.Net.NetworkCredential("info@MyWebsiteDomainName.com", "myIDPassword");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
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);

Thamotharan的景点就在附近。发送纯文本或HTML正文。用于快速而肮脏的普通电子邮件。这是在邮件正文中嵌入HTML标记的一个很好的示例。内联HTML代码。StringBuilder对于创建较大的消息非常有用。另外
Bryan Springborn 2013年

13
我发现这很有帮助。根据文档,尽管将UseDefaultCredentials设置为true意味着将不发送给定的凭据。这是要弄清楚的棘手部分。
Garr Godfrey 2014年

11
请注意这两个MailMessageSmtpClient实施IDisposable,并应有一套内使用using语句(或以其他方式处置)
taiji123

24

尝试改用此代码。注意:在“发件人地址”中,输入正确的电子邮件ID和密码。

protected void btn_send_Click(object sender, EventArgs e)
{

    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
    mail.To.Add("to gmail address");
    mail.From = new MailAddress("from gmail address", "Email head", System.Text.Encoding.UTF8);
    mail.Subject = "This mail is send from asp.net application";
    mail.SubjectEncoding = System.Text.Encoding.UTF8;
    mail.Body = "This is Email Body Text";
    mail.BodyEncoding = System.Text.Encoding.UTF8;
    mail.IsBodyHtml = true;
    mail.Priority = MailPriority.High;
    SmtpClient client = new SmtpClient();
    client.Credentials = new System.Net.NetworkCredential("from gmail address", "your gmail account password");
    client.Port = 587;
    client.Host = "smtp.gmail.com";
    client.EnableSsl = true;
    try
    {
        client.Send(mail);
        Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');if(alert){ window.location='SendMail.aspx';}</script>");
    }
    catch (Exception ex)
    {
        Exception ex2 = ex;
        string errorMessage = string.Empty;
        while (ex2 != null)
        {
            errorMessage += ex2.ToString();
            ex2 = ex2.InnerException;
        }
        Page.RegisterStartupScript("UserMsg", "<script>alert('Sending Failed...');if(alert){ window.location='SendMail.aspx';}</script>");
    }
}

因此,我在ASP.net页中使用dropdownlist / textboxes设置了一个表单。它会以相同的方式工作吗?谢谢。
SearchForKnowledge

此代码在本地服务器bot上起作用,而不是从托管Goddady服务器起。为什么?
Sam Alex

10

您可以使用hotmail尝试如下操作:-

MailMessage o = new MailMessage("From", "To","Subject", "Body");
NetworkCredential netCred= new NetworkCredential("Sender Email","Sender Password");
SmtpClient smtpobj= new SmtpClient("smtp.live.com", 587); 
smtpobj.EnableSsl = true;
smtpobj.Credentials = netCred;
smtpobj.Send(o);

9

尝试以下方法:

try
{
    var fromEmailAddress =  ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
    var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
    var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
    var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
    var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();

    string body = "Your registration has been done successfully. Thank you.";
    MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName), new MailAddress(ud.LoginId, ud.FullName));
    message.Subject = "Thank You For Your Registration";
    message.IsBodyHtml = true;
    message.Body = body;

    var client = new SmtpClient();
    client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
    client.Host = smtpHost;
    client.EnableSsl = true;
    client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
    client.Send(message);
}
catch (Exception ex)
{
    throw (new Exception("Mail send failed to loginId " + ud.LoginId + ", though registration done."));
}

然后在您的web.config中添加以下内容

<!--Email Config-->
<add key="FromEmailAddress" value="sender emailaddress"/>
<add key="FromEmailDisplayName" value="Display Name"/>
<add key="FromEmailPassword" value="sender Password"/>
<add key="SMTPHost" value="smtp-proxy.tm.net.my"/>
<add key="SMTPPort" value="smptp Port"/>

3

您可以尝试MailKit MailKit是一个基于MimeKit并针对移动设备进行了优化的开源跨平台.NET邮件客户端库。您可以在应用程序中轻松使用。可以从此处下载。

                MimeMessage mailMessage = new MimeMessage();
                mailMessage.From.Add(new MailboxAddress(fromName, from@address.com));
                mailMessage.Sender = new MailboxAddress(senderName, sender@address.com);
                mailMessage.To.Add(new MailboxAddress(emailid, emailid));
                mailMessage.Subject = subject;
                mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
                mailMessage.Subject = subject;
                var builder = new BodyBuilder();
                builder.TextBody = "Hello There";           
                try
                {
                    using (var smtpClient = new SmtpClient())
                    {
                        smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
                        smtpClient.Authenticate("user@name.com", "password");

                        smtpClient.Send(mailMessage);
                        Console.WriteLine("Success");
                    }
                }
                catch (SmtpCommandException ex)
                {
                    Console.WriteLine(ex.ToString());              
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());                
                }              

2

检查出来....它的工作原理

http://www.aspnettutorials.com/tutorials/email/email-aspnet2-csharp/

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage message = new MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
            SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
            emailClient.Send(message);
            litStatus.Text = "Message Sent";
        }
        catch (Exception ex)
        {
            litStatus.Text=ex.ToString();
        }
    }
}

:上面的链接不起作用,在这里你可以检查一步一步的指导,以发送电子邮件的ASP网网络形式qawithexperts.com/article/asp-net/...
user3559462

0

如果要用剃刀生成电子邮件正文,可以使用Mailzory。另外,您可以从此处下载nuget软件包。

// template path
var viewPath = Path.Combine("Views/Emails", "hello.cshtml");
// read the content of template and pass it to the Email constructor
var template = File.ReadAllText(viewPath);

var email = new Email(template);

// set ViewBag properties
email.ViewBag.Name = "Johnny";
email.ViewBag.Content = "Mailzory Is Funny";

// send email
var task = email.SendAsync("mailzory@outlook.com", "subject");
task.Wait()

0

根据这个 :

SmtpClient及其类型的网络设计不良,我们强烈建议您改用https://github.com/jstedfast/MailKithttps://github.com/jstedfast/MimeKit

参考:https : //docs.microsoft.com/zh-cn/dotnet/api/system.net.mail.smtpclient?view=netframework-4.8

最好使用MailKit发送电子邮件:

var message = new MimeMessage ();
            message.From.Add (new MailboxAddress ("Joey Tribbiani", "joey@friends.com"));
            message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "chandler@friends.com"));
            message.Subject = "How you doin'?";

            message.Body = new TextPart ("plain") {
                Text = @"Hey Chandler,
I just wanted to let you know that Monica and I were going to go play some paintball, you in?
-- Joey"
            };

            using (var client = new SmtpClient ()) {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s,c,h,e) => true;

                client.Connect ("smtp.friends.com", 587, false);

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate ("joey", "password");

                client.Send (message);
                client.Disconnect (true);
            }

-1
MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text);
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (fuAttachment.HasFile)//file upload select or not
{
    string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
    mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
Response.write("Send Mail");

观看视频:https : //www.youtube.com/watch?v=bUUNv-19QAI


-1

这是最容易测试的脚本。

<%@ Import Namespace="System.Net" %> 
<%@ Import Namespace="System.Net.Mail" %> 

<script language="C#" runat="server"> 
    protected void Page_Load(object sender, EventArgs e) 
    { 
       //create the mail message 
        MailMessage mail = new MailMessage(); 

        //set the addresses 
        mail.From = new MailAddress("From email account"); 
        mail.To.Add("To email account"); 

        //set the content 
        mail.Subject = "This is a test email from C# script"; 
        mail.Body = "This is a test email from C# script"; 
        //send the message 
         SmtpClient smtp = new SmtpClient("mail.domainname.com"); 

         NetworkCredential Credentials = new NetworkCredential("to email account", "Password"); 
         smtp.Credentials = Credentials;
         smtp.Send(mail); 
         lblMessage.Text = "Mail Sent"; 
    } 
</script> 
<html> 
<body> 
    <form runat="server"> 
        <asp:Label id="lblMessage" runat="server"></asp:Label> 
    </form> 
</body>

1
您为什么选择将其放在视图中而不让控制器处理呢?
WhatsThePoint

刚问过有关通过ASP.NET C#发送电子邮件的问题。没有提到在脚本中设置控制器。
埃伦·帕吉
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.