以aspnet身份发送电子邮件

时间:2017-01-11 03:16:50

标签: c# asp.net-mvc email asp.net-identity

我写了以下方法来发送电子邮件

public ActionResult SendEmail(UserData user)
{
    try
    {
        #region Email content

        MailMessage m = new MailMessage(
        new MailAddress("sender@email.com", "Represent Location"),
        new MailAddress(Reciever_Email));
        m.Subject = "Mail Topic";

        m.IsBodyHtml = true;

        m.Body = string.Format("<img src=\"@@IMAGE@@\" alt=\"\"><BR/><BR/>Hi " + user.FirstName + "," + "<BR/><BR/>Your account has been successfully created with the Comp. Please click on the link below to access your account.<BR/><BR/>" + "Username - " + user.UserName + "<BR/>" + "Password - " + user.Password + "<BR/><BR/>" + "<a href=\"{1}\" title=\"User Email Confirm\">Please click here to Activate your account</a>", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.Id, Email = user.UserEmail }, Request.Url.Scheme)) + string.Format("<BR/><BR/>Regards,<BR/>The Human Resource Department <BR/>");

        // create the INLINE attachment      
        string attachmentPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.jpg");

        // generate the contentID string using the datetime
        string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm";

        Attachment inline = new Attachment(attachmentPath);
        inline.ContentDisposition.Inline = true;
        inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
        inline.ContentId = contentID;
        inline.ContentType.MediaType = "image/png";
        inline.ContentType.Name = Path.GetFileName(attachmentPath);
        m.Attachments.Add(inline);

        // replace the tag with the correct content ID
        m.Body = m.Body.Replace("@@IMAGE@@", "cid:" + contentID);

        SmtpClient smtp = new SmtpClient("Email_Server_IP");
        smtp.Port = ServerPort;
        smtp.Credentials = new NetworkCredential("sender@email.com", "sender_password");
        smtp.EnableSsl = false;
        smtp.Send(m);

        #endregion

        return View(user);

    }

    catch (Exception ex)
    {
        throw ex;
    }
}

然后我在主控制器中访问上面的方法,如下面的

// Email Sending
UserData sampleData = new UserData();
sampleData.Id = user.Id;
sampleData.UserName = user.UserName;
sampleData.UserEmail = user.Email;
sampleData.FirstName = user.FirstName;
sampleData.Password = model.Password;

// await EmailController.Sendemail(sampleData);
var emailCntrl = new EmailController();
var sendEmail = emailCntrl.SendEmail(sampleData);

这是编译时没有任何编译时错误。但是当我调试这个时,我可以看到

在这一行m.Body = str...我可以看到像这样的错误

enter image description here

因为我得到了例外

  

Message =“对象引用未设置为对象的实例。”

我该如何解决?

3 个答案:

答案 0 :(得分:0)

考虑到在调用action之前没有向控制器添加请求,它将为null。

那里不需要控制器来发送电子邮件。

创建一个类/服务来处理电子邮件并传入任何依赖项

public class EmailService {

    public UserData SendEmail(UserData user, string confirmationEmailUrl) {
        try
        {
            #region Email content

            MailMessage m = new MailMessage(
            new MailAddress("sender@email.com", "Represent Location"),
            new MailAddress(Reciever_Email));
            m.Subject = "Mail Topic";

            m.IsBodyHtml = true;

            m.Body = string.Format("<img src=\"@@IMAGE@@\" alt=\"\"><BR/><BR/>Hi " + user.FirstName + "," + "<BR/><BR/>Your account has been successfully created. Please click on the link below to access your account.<BR/><BR/>" + "Username - " + user.UserName + "<BR/>" + "Password - " + user.Password + "<BR/><BR/>" + "<a href=\"{1}\" title=\"User Email Confirm\">Please click here to Activate your account</a>", user.UserName, confirmationEmailUrl + string.Format("<BR/><BR/>Regards,<BR/>The Human Resource Department <BR/>");

            // create the INLINE attachment      
            string attachmentPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.jpg");

            // generate the contentID string using the datetime
            string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm";

            Attachment inline = new Attachment(attachmentPath);
            inline.ContentDisposition.Inline = true;
            inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
            inline.ContentId = contentID;
            inline.ContentType.MediaType = "image/png";
            inline.ContentType.Name = Path.GetFileName(attachmentPath);
            m.Attachments.Add(inline);

            // replace the tag with the correct content ID
            m.Body = m.Body.Replace("@@IMAGE@@", "cid:" + contentID);

            SmtpClient smtp = new SmtpClient("Email_Server_IP");
            smtp.Port = ServerPort;
            smtp.Credentials = new NetworkCredential("sender@email.com", "sender_password");
            smtp.EnableSsl = false;
            smtp.Send(m);

            #endregion

            return user;

        }

        catch (Exception ex)
        {
            throw ex;
        }
    }
}

从主控制器获取动作

// Email Sending
UserData sampleData = new UserData();
sampleData.Id = user.Id;
sampleData.UserName = user.UserName;
sampleData.UserEmail = user.Email;
sampleData.FirstName = user.FirstName;
sampleData.Password = model.Password;

var confirmationEmailUrl = Url.Link("Default", new { Action = "ConfirmEmail", Controller = "Account",  Token = sampleData.Id, Email = sampleData.UserEmail });

var emailService = new EmailService();
var user = emailService.SendEmail(sampleData, confirmationEmailUrl);

答案 1 :(得分:0)

您没有请求,因为您只创建了EmailController课程。当控制器工厂为请求创建控制器时,它将请求数据传递给Controller.Initialize Method

当然,最佳做法是如上所述创建EmailService,但作为问题的答案,您可以进行解决方法。您可以将RequestContext父控制器传递给构造函数中的EmailController并调用Initialize。它看起来会像。

    public EmailController()
    {
    }

    public EmailController(RequestContext requestContext)
    {
        base.Initialize(requestContext);
    }

在您的控制器中

var emailCntrl = new EmailController(this.ControllerContext.RequestContext);
var sendEmail = emailCntrl.SendEmail(sampleData);

答案 2 :(得分:0)

您也可以设置ControllerContext

var emailCntrl = new EmailController(){ControllerContext = this.ControllerContext};
var sendEmail = emailCntrl.SendEmail(sampleData);