MVC 4从网站向客户发送邮件

时间:2013-09-27 05:05:57

标签: c# asp.net-mvc-4 azure smtp

所以我有一个发布到Azure的数据库程序MVC4,C#。

代理将在数据库中创建记录,然后客户端将查看它们。记录只能由代理创建或编辑。

我遇到的麻烦是邮件功能。我希望有一个功能,以便当代理点击保存时,无论是在编辑还是创建之后,都会向客户端发送一封电子邮件,引用该记录。该电子邮件将包含一个记录定位器。客户端电子邮件和记录定位器是每条记录中的项目。

我得到了表格,但是我遇到了控制器和System.Main.Net的问题。我的编辑控制器代码如下。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TrepPortal.Models;
using System.Net.Mail;

    //
    // GET: /AgntActions/Edit/5

    public ActionResult Edit(int id = 0)
    {
        ClientActions clientactions = db.ClientActions.Find(id);
        if (clientactions == null)
        {
            return HttpNotFound();
        }
        return View(clientactions);
    }

    //
    // POST: /AgntActions/Edit/5


    [HttpPost]
    public ActionResult Edit(ClientActions clientactions)
    {
        if (ModelState.IsValid)
        {
            db.Entry(clientactions).State = EntityState.Modified;
            db.SaveChanges();

            //mail function
            MailMessage message = new MailMessage();
            message.From = new MailAddress("nick@cooktravel.net");
            //message.To.Add(new MailAddress("nick@cooktravel.net"));
            message.To.Add(clientactions.ClientEmail);
            message.Subject = "This is my subject";
            message.Body = "Your Cook Travel reservation has been updated. The record locator is "clientactions.SabreLocator" . Please visit cooktravelportal.net to view it.";

            //SmtpClient client = new SmtpClient("smtp.cooktravel.net, 495");//old
            SmtpClient client = new SmtpClient("smtp.cooktravel.net", 25);//

            client.UseDefaultCredentials = false;
            client.EnableSsl = false;
            client.Credentials = new System.Net.NetworkCredential("nick@cooktravel.net", "Password");
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            client.Send(message); //on debug, error comes here as SmtpException unhandled

            return RedirectToAction("Index");
        }
        return View(clientactions);
    }

现在我没有很多经验。我通过阅读许多文章和例子把它放在一起。另外,如果我遗漏任何使用声明,请告诉我。任何反馈都表示赞赏。谢谢!

27SEP13评论:“SmptException未被用户代码处理。” “邮件发送失败。”在上面标记的行调试中出现此错误,“client.Send(message)” 好的,由于当前的答案,我更改了部分代码以正确指示上面标记的端口,但现在我收到以下错误。

[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its   access permissions 66.179.170.244:25]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +208
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +464

[WebException: Unable to connect to the remote server]
System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async,   IPAddress& address, Socket& abortSocket, Socket& abortSocket6) +6470692
System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback) +307
System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +19
System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +324
System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) +141
System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint) +170
System.Net.Mail.SmtpClient.GetConnection() +44
System.Net.Mail.SmtpClient.Send(MailMessage message) +1554

5 个答案:

答案 0 :(得分:3)

也许你需要修改这行代码:

SmtpClient client = new SmtpClient("smtp.cooktravel.net, 495");

SmtpClient client = new SmtpClient("smtp.cooktravel.net",495);

答案 1 :(得分:1)

您可以尝试更改:

  SmtpClient client = new SmtpClient("smtp.cooktravel.net, 495");

致:

SmtpClient client = new SmtpClient("smtp.cooktravel.net");
client.Port = 495;

或者您可以显示使用例外细节吗?

答案 2 :(得分:0)

view 
<% using(Html.BeginForm("Sendlink", "Home")) %>
    <% { %>
     <input type="text" id="toemail" value="" />
        <input type="submit" value="Send" />
    <% } %>
Controller
public ActionResult Sendlink()
{
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Sendlink(FormCollection formCollection)
{
    try
    {
        string message = Session["link"].ToString();
        string toemail = formCollection["toemail"];
        MailEngine.Send("mail@mail.com", toemail, "link", message);
        return RedirectToAction("CanvasShare");
    }
    catch
    {

    }
    return null;
}

Code (Model)




I am trying to send an email inside an action. However, the action always returns a blank screen.

View:

<% using(Html.BeginForm("Sendlink", "Home")) %>
    <% { %>
     <input type="text" id="toemail" value="" />
        <input type="submit" value="Send" />
    <% } %>

Controller:

public ActionResult Sendlink()
{
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Sendlink(FormCollection formCollection)
{
    try
    {
        string message = Session["link"].ToString();
        string toemail = formCollection["toemail"];
        MailEngine.Send("mail@mail.com", toemail, "link", message);
        return RedirectToAction("CanvasShare");
    }
    catch
    {

    }
    return null;
}

Class MailEngine:

public static void Send(string from, string to, string subject, string body)
{
    try
    {
        MailMessage mail = new MailMessage(from, to, subject, body);
        SmtpClient client = new SmtpClient("smtp.mymail.com");
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.EnableSsl = false;
        client.Send(mail);
    }
    catch
    {

    }
}`enter code here`

答案 3 :(得分:0)

System.Net.Mail正确支持localhost上的25个端口,我花了很多时间才找到一篇文章,详细解释了这个问题。

也许它会对你有所帮助:

            string from = "";
            string fromPass = "";

            MailMessage eMail = new MailMessage();
            eMail.IsBodyHtml = true;
            eMail.Body = message;
            eMail.From = new MailAddress(from);
            eMail.To.Add(address);
            eMail.Subject = subject;
            SmtpClient SMTP = new SmtpClient();

            SMTP.Credentials = new NetworkCredential(from, fromPass);
            SMTP.Host = "localhost";
            SMTP.Send(eMail);

编辑:如果您需要使用465或其他端口,则需要使用单个库

答案 4 :(得分:0)

@Jayraj

显然,你的try块里面有一些错误。它捕获了错误,但你没有做任何事情。我怀疑这是你的Session [“link”],它是null。在ActionResult中返回null将导致空白屏幕。