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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-4 – 如何在asp.net mvc应用程序中使用Gmail SMTP发送电子邮件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在他/她在我的网站注册时向用户发送一封邮件.

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

请帮助我这方面.

谢谢,
玉萍

解决方法

创建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();

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

原文链接:https://www.f2er.com/aspnet/251456.html

猜你在找的asp.Net相关文章