在MVC3中向Gmail发送注册链接

时间:2013-07-01 13:35:01

标签: asp.net-mvc

我想在第一次注册用户时将注册链接发送到Gmail帐户,我的意思是检查用户电子邮件地址的真实性。我已经实现了这一点但我的问题是用户没有获得任何链接和消息正文。如果我在我的函数中定义这两个,它会给我错误。这是我的功能,它给了我以下错误:

  

“非静态字段,方法或者需要对象引用   属性'System.Web.Mvc.Controller.HttpContext.get'“和语法错误   for message.body =“”。

我该怎么做?

public class EmailManager
{
    private const string EmailFrom = "noreplay@gmail.com";
    public static void SendConfirmationEmail(string userName)
    {
        var user = Membership.GetUser(userName.ToString());
        var confirmationGuid = user.ProviderUserKey.ToString();
        //var verifyUrl = HttpContext.Current.Request.Url.GetLeftPart
        //   (UriPartial.Authority) + "/Account/Verify/" + confirmationGuid;

        using (var client = new SmtpClient())
        {
            using (var message = new MailMessage(EmailFrom, user.Email))
            {
                message.Subject = "Please Verify your Account";
//              message.Body = "To verify your account, please click the following link:"
//+ "<a href=\"" + verifyUrl + "\" target=\"_blank\">" + verifyUrl + "
//+"</a></p><div>Best regards,</div><div>Someone</div><p>Do not forward "
//+"this email. The verify link is private.</p></body></html>";

                message.IsBodyHtml = true;
                client.EnableSsl = true;
                client.Send(message);
            };
        };
    }
}

请帮助我。

1 个答案:

答案 0 :(得分:0)

你的意思是你的HttpContext.Current.Request.Url.GetLeftPart会抛出错误。这是正确的,因为你在班级EmailManager,而你实际上是指访问Controller的上下文。

所以改变你的签名:

SendConfirmationEmail(string userName, string verifyUrl)
{

}

从控制器传递它:

public class YourController : Controller
{
    public ActionResult Register()
    {
        [...]

        var verifyUrl = HttpContext.Current.Request.Url.GetLeftPart;
        var mailManager = new MailManager();

        mailManager.SendConfirmationEmail("TestUser", verifyUrl);

        [...]
    }
}