Cara mengirim email di ASP.NET C #

91

Saya sangat baru di area ASP.NET C #. Saya berencana mengirim email melalui ASP.NET C # dan ini adalah alamat SMTP dari ISP saya :

smtp-proxy.tm.net.my

Di bawah ini adalah apa yang saya coba lakukan, tetapi gagal.

<%@ 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>

Dan di bawah ini adalah kode di belakang saya :

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: Maaf saya tidak bisa memahami konsep SMTP penerima / pengirim, jadi saya mencoba untuk memahami konsep keseluruhan dari sini.

SuicideSheep
sumber
Ketika Anda mengklik tombol, apakah itu mencapai kode di belakang?
Conrad Lotz
Apakah Anda menyiapkan smtp di IIS di localhost? Apa kegagalannya? Apakah Anda memiliki akun email dengan ISP Anda?
mrtig

Jawaban:

115

Cukup buka kode di bawah ini.

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

smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "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("[email protected]"));

smtpClient.Send(mail);
Thamotharan Karuppiah
sumber
Thamotharan tepat. Mengirim teks biasa atau badan HTML. Untuk email biasa yang cepat dan kotor. Berikut adalah contoh yang bagus untuk menyematkan tag HTML di dalam badan pesan. Kode HTML sebaris . StringBuilder sangat berguna untuk membuat pesan yang lebih besar. Juga
Bryan Springborn
13
saya menemukan ini bermanfaat. meskipun menyetel UseDefaultCredentials ke true berarti Kredensial yang diberikan tidak akan dikirim, menurut dokumentasi. Itu bagian yang sulit untuk dipecahkan.
Garr Godfrey
11
Perhatikan bahwa keduanya MailMessagedan SmtpClientimplementasikan IDisposabledan harus digunakan dalam usingpernyataan (atau dibuang)
taiji123
24

Coba gunakan kode ini sebagai gantinya. Catatan: Di kolom "from address" berikan id email dan password yang benar.

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>");
    }
}
Thangamalai
sumber
Jadi saya memiliki formulir yang disiapkan di halaman ASP.net saya dengan dropdownlist / kotak teks. Akankah ini bekerja dengan cara yang sama? Terima kasih.
SearchForKnowledge
Kode ini bekerja pada bot server lokal bukan dari hosting server goddady .. Kenapa?
Sam Alex
10

Anda dapat mencoba ini menggunakan hotmail seperti ini: -

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);
Rahul Tripathi
sumber
9

Coba yang berikut ini:

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."));
}

Dan kemudian di web.config Anda, tambahkan yang berikut ini di antara

<!--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"/>
Krishna
sumber
3

Anda dapat mencoba MailKit MailKit adalah pustaka klien email lintas platform .NET Sumber Terbuka yang didasarkan pada MimeKit dan dioptimalkan untuk perangkat seluler. Anda dapat menggunakan dengan mudah di aplikasi Anda. Anda dapat mendownload dari sini .

                MimeMessage mailMessage = new MimeMessage();
                mailMessage.From.Add(new MailboxAddress(fromName, from@address.com));
                mailMessage.Sender = new MailboxAddress(senderName, [email protected]);
                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("[email protected]", "password");

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

Lihat ini .... berhasil

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();
        }
    }
}
Aditya
sumber
link di atas tidak berfungsi, di sini Anda dapat memeriksa panduan langkah demi langkah untuk mengirim email dalam bentuk web asp net: qawithexperts.com/article/asp-net/…
user3559462
0

Jika Anda ingin membuat badan email Anda di pisau cukur, Anda dapat menggunakan Mailzory . Anda juga dapat mengunduh paket nuget dari sini .

// 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("[email protected]", "subject");
task.Wait()
Ehsan Mirsaeedi
sumber
0

Menurut Ini :

SmtpClient dan jenis jaringannya dirancang dengan buruk, kami sangat menyarankan Anda menggunakan https://github.com/jstedfast/MailKit dan https://github.com/jstedfast/MimeKit sebagai gantinya.

Referensi: https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=netframework-4.8

Lebih baik digunakan MailKituntuk mengirim email:

var message = new MimeMessage ();
            message.From.Add (new MailboxAddress ("Joey Tribbiani", "[email protected]"));
            message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "[email protected]"));
            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);
            }
AminSojoudi
sumber
-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");

Lihat Video: https://www.youtube.com/watch?v=bUUNv-19QAI

jishan siddique
sumber
-1

Ini adalah skrip termudah untuk diuji.

<%@ 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>
Hiren Parghi
sumber
1
mengapa Anda memilih untuk menaruhnya dalam tampilan dan tidak membiarkan pengontrol menangani ini?
WhatsThePoint
Pertanyaannya baru saja ditanyakan tentang pengiriman email melalui ASP.NET C #. Tidak disebutkan untuk mengatur pengontrol dalam skrip.
Hiren Parghi