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

时间:2017-05-23 03:25:33

标签: smtp gmail gsuite

此代码在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 = "seong@abcd.net";

            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 = "seong@abcd.net";
                    credentials.Password = "1234";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = credentials;
                    smtp.Port = 587;
                    smtp.Send(mm);
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我解决了这个问题。 如果您想使用SMTP,该帐户不应在Gmail中使用第二次验证。

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

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

答案 1 :(得分:0)

商务套件的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;
}