SMTP不会在Gmail帐户中发送电子邮件

问题描述 投票:1回答:2

此代码在gmail个人帐户中运行良好,但是当我尝试使用gmail商业帐户时,它无法正常运行并且一直出错。 5.5.1需要验证。

void SendEmail()
{
    DataTable data = GetData();
    DataTable email_data = GetEmailData();
    data.TableName = "Employee_Data";

    using (XLWorkbook wb = new XLWorkbook())
    {
        wb.Worksheets.Add(data);

        using (MemoryStream memoryStream = new MemoryStream())
        {
            wb.SaveAs(memoryStream);
            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            String from = "[email protected]";

            for (int i = 0; i < email_data.Rows.Count; i++)
            {
                String to = email_data.Rows[i][0].ToString();

                using (MailMessage mm = new MailMessage(from, to))
                {
                    mm.Subject = "Employees Attachment";
                    mm.Body = "Employees Exported Attachment";

                    mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "Employees.xlsx"));
                    mm.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                    credentials.UserName = "[email protected]";
                    credentials.Password = "1234";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = credentials;
                    smtp.Port = 587;
                    smtp.Send(mm);
                }
            }
        }
    }
}
smtp gmail gsuite
2个回答
0
投票

我解决了这个问题。如果要使用SMTP,则帐户不应在gmail中使用第二次验证。

https://support.google.com/accounts/answer/1064203?hl=en&ref_topic=7189195

我无法控制那些东西,我要求管理员允许不使用第二次验证。所以我可以使用SMTP使用该帐户。


0
投票

商业Gsuite的Smtp方法

require_once('class.phpmailer.php');

$mail = new PHPMailer(); // defaults to using php "mail()"
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true; 
$mail->Port = 587;
$mail->Host = "smtp.gmail.com";
$mail->Username   = "Enter the user ID"; // SMTP account username
// SMTP account password
$mail->Password   = "Enter your password";

$mail->SetFrom('Enter the User ID', 'Subject');
$mail->AddReplyTo("Enter the User ID", "Subject");

$mail->AddAddress($to, "Name");

$mail->Subject    = "Contact Enquiry";

$message = '';

$mail->MsgHTML($message);

if($mail->Send()){
   $mail->ClearAddresses();  
   echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
} else {
     echo "Mailer Error: " . $mail->ErrorInfo;
}
© www.soinside.com 2019 - 2024. All rights reserved.