12

C# で asp.net プロジェクトを使用して、コンピューター (localhost) から電子メールを送信することは可能ですか? 最後に、プロジェクトを Web サーバーにアップロードしますが、アップロードする前にテストしたいと思います。

準備ができているソース コードを見つけて、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# を使用してメールを送信する方法は? サーバー構成をセットアップする必要がありますか?

4

8 に答える 8

12

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);
于 2012-07-28T19:43:32.970 に答える
7

if you have a gmail account you can use google smtp to send an email

smtpClient.UseDefaultCredentials = false;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Credentials = new NetworkCredential(username,passwordd);
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
于 2012-07-28T19:39:17.933 に答える
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 はすでにこれを行っています。

于 2012-07-28T20:24:05.867 に答える
2

You can send email from ASP.NET via C# class libraries found in the System.Net.Mail namespace. take a look at the SmtpClient class which is the main class involved when sending emails.

You can find code examples in Scott Gu's Blog or on the MSDN page of SmtpClient.

Additionally you'll need an SMTP server running. I can recommend to use SMTP4Dev mail server that targets development and does not require any setup.

于 2012-07-28T19:42:11.730 に答える
1
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 = "";
    }
于 2012-08-06T11:03:39.967 に答える
0

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://dotnetawsome.blogspot.in/2013/09/send-email-with-attachment-using-cnet.htmlにアクセスしてください。

于 2013-10-06T08:46:04.167 に答える