如何在asp.net mvc应用程序中使用Gmail SMTP发送电子邮件?

时间:2014-01-02 12:22:27

标签: asp.net-mvc-4 smtp gmail

我想在他/她在我的网站注册时向用户发送一封邮件。

我已经创建了我的gmail帐户,我已经尝试了很多来自网络的样本,但我还是无法发送电子邮件。

请帮助我。

谢谢, 维基

4 个答案:

答案 0 :(得分:25)

我发现了一篇关于在C#中使用Gmail SMTP的非常好的文章,所以我与您分享:https://askgif.com/blog/122/seding-email-using-gmail-smtp-in-asp-net-mvc-application/

创建Gmail类包含所有需要的数据类型和成员函数,如下所示

public class GMailer
{
    public static string GmailUsername { get; set; }
    public static string GmailPassword { get; set; }
    public static string GmailHost { get; set; }
    public static int GmailPort { get; set; }
    public static bool GmailSSL { get; set; }

    public string ToEmail { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
    public bool IsHtml { get; set; }

    static GMailer()
    {
        GmailHost = "smtp.gmail.com";
        GmailPort = 25; // Gmail can use ports 25, 465 & 587; but must be 25 for medium trust environment.
        GmailSSL = true;
    }

    public void Send()
    {
        SmtpClient smtp = new SmtpClient();
        smtp.Host = GmailHost;
        smtp.Port = GmailPort;
        smtp.EnableSsl = GmailSSL;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential(GmailUsername, GmailPassword);

        using (var message = new MailMessage(GmailUsername, ToEmail))
        {
            message.Subject = Subject;
            message.Body = Body;
            message.IsBodyHtml = IsHtml;
            smtp.Send(message);
        }
    }
}

然后只需使用以下代码将电子邮件发送到所需的电子邮件帐户。

GMailer.GmailUsername = "youremailid@gmail.com";
        GMailer.GmailPassword = "YourPassword";

        GMailer mailer = new GMailer();
        mailer.ToEmail = "sumitchourasia91@gmail.com";
        mailer.Subject = "Verify your email id";
        mailer.Body = "Thanks for Registering your account.<br> please verify your email id by clicking the link <br> <a href='youraccount.com/verifycode=12323232'>verify</a>";
        mailer.IsHtml = true;
        mailer.Send();

希望这会对你有所帮助。 如果这有助于你,请标记为答案。

答案 1 :(得分:3)

这是一个可以与ASP.NET MVC4一起使用依赖注入的Email类。完整运行的示例应用程序&amp;可以在我的github空间https://github.com/fredo007/i6technology/tree/master/InsuranceSales中找到使用此类的单元测试。

我还汇总了一篇解释方法论的文章。在这里使用http://prestoasp.net/how-to-send-email-using-gmail-smtp-in-an-asp-net-mvc-application/

public class GmailEmailService : IEmailService
{
    private readonly SmtpConfiguration _config;

    private const string GmailUserNameKey = "GmailUserName";
    private const string GmailPasswordKey = "GmailPassword";
    private const string GmailHostKey = "GmailHost";
    private const string GmailPortKey = "GmailPort";
    private const string GmailSslKey = "GmailSsl";

    public GmailEmailService()
    {
        _config = new SmtpConfiguration();
        var gmailUserName = ConfigurationManager.AppSettings[GmailUserNameKey];
        var gmailPassword = ConfigurationManager.AppSettings[GmailPasswordKey];
        var gmailHost = ConfigurationManager.AppSettings[GmailHostKey];
        var gmailPort = Int32.Parse(ConfigurationManager.AppSettings[GmailPortKey]);
        var gmailSsl = Boolean.Parse(ConfigurationManager.AppSettings[GmailSslKey]);
        _config.Username = gmailUserName;
        _config.Password = gmailPassword;
        _config.Host = gmailHost;
        _config.Port = gmailPort;
        _config.Ssl = gmailSsl;
    }

    public bool SendEmailMessage(EmailMessage message)
    {
        var success = false;
        try
        {
            var smtp = new SmtpClient
            {
                Host = _config.Host,
                Port = _config.Port,
                EnableSsl = _config.Ssl,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(_config.Username, _config.Password)
            };

            using (var smtpMessage = new MailMessage(_config.Username, message.ToEmail))
            {
                smtpMessage.Subject = message.Subject;
                smtpMessage.Body = message.Body;
                smtpMessage.IsBodyHtml = message.IsHtml;
                smtp.Send(smtpMessage);
            }

            success = true;
        }
        catch (Exception ex)
        {
            //todo: add logging integration
            //throw;
        }

        return success;
    }
}

答案 2 :(得分:2)

除了fredo,请回答清除web.config部分

public GmailEmailService()
{
    _config = new SmtpConfiguration();
    var gmailUserName = ConfigurationManager.AppSettings[GmailUserNameKey];
    var gmailPassword = ConfigurationManager.AppSettings[GmailPasswordKey];
    var gmailHost = ConfigurationManager.AppSettings[GmailHostKey];
    var gmailPort = Int32.Parse(ConfigurationManager.AppSettings[GmailPortKey]);
    var gmailSsl = Boolean.Parse(ConfigurationManager.AppSettings[GmailSslKey]);
    _config.Username = gmailUserName;
    _config.Password = gmailPassword;
    _config.Host = gmailHost;
    _config.Port = gmailPort;
    _config.Ssl = gmailSsl;
}

现在添加web.config文件

<configuration>
    <appSettings>
        <add key="GmailUserNameKey" value="sender@gmail.com"/>
        <add key="GmailPasswordKey" value="senderPassword"/>
        <add key="GmailHostKey" value="smtp.gmail.com"/>
        <add key="GmailPortKey" value="25"/>
        <add key="GmailSslKey" value="true"/>
</appSettings>

答案 3 :(得分:-1)

这是我的解决方案,第一次发布答案。快乐的编码

[HttpPost]
[ValidateAntiForgeryToken]
public async Task < ActionResult > Contact(EmailFormModel model) {
    if (ModelState.IsValid) {
        var body = "<p>Email From: {0} ({1})Message:</p><p>{2}</p>";
        var message = new MailMessage();
        //message.To.Add(new MailAddress("recipient@gmail.com"));  // replace with valid value 
        message.To.Add(new MailAddress("haha")); // replace with valid value 
        //message.From = new MailAddress("sender@outlook.com");  // replace with valid value
        message.From = new MailAddress("hahaha"); // replace with valid value,you cannot commend it, since it's required
        message.Subject = "Your email subject";
        message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
        message.IsBodyHtml = true;

        using(var smtp = new SmtpClient()) {
            var credential = new NetworkCredential {
                UserName = "emailAddress", // replace with valid value
                    Password = "yourPassword" // Password = "password"  // replace with valid value
            };
            //smtp.Credentials = credential;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new System.Net.NetworkCredential("your emailAddress", "Password"); //You will be receive email from this email address
            //smtp.Host = "smtp-mail.outlook.com";
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.EnableSsl = true;
            await smtp.SendMailAsync(message);
            return RedirectToAction("Sent");
        }
    }
    return View(model);
}