邮件没有发送

时间:2016-09-24 09:47:14

标签: c# c#-4.0

void sendMail(string invoiceNumber)
{
    try
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("Smtp.gmail.com");
        mail.From = new MailAddress("*******@gmail.com");
        mail.To.Add("******@gmail.com");
        mail.Subject = "Test Mail - 1";
        mail.Body = invoiceNumber;
        mail.Subject = "PDFs Attached";
        DirectoryInfo di = new DirectoryInfo(@"C:\Users\User\Desktop\test\");
        foreach (var file in di.GetFileSystemInfos("*.pdf*"))
            mail.Attachments.Add(new Attachment(file.FullName));
        SmtpServer.Port = 587;
        SmtpServer.Credentials = new System.Net.NetworkCredential("*******@gmail.com", "*********");
        SmtpServer.EnableSsl = true;
        SmtpServer.Send(mail);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

1 个答案:

答案 0 :(得分:0)

https://www.google.com/settings/security/lesssecureapps使用此链接允许您的Gmail帐号允许安全性较低的应用....

void sendMail(string invoiceNumber)
{
    try
    {
        MailMessage mail = new MailMessage();
            mail.To.Add("recevermailid");
            mail.From = new MailAddress("sender id");
            mail.Subject = "Confirmation";
            string Body = "your message body";
            mail.Body = Body; 
            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new System.Net.NetworkCredential
            ("sender email", "seneder email password");// Enter seders User name and password
            smtp.EnableSsl = true;
            smtp.Send(mail);

    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}