当我尝试向客户发送电子邮件时,很抱歉向他们发送电子邮件。
我看了here:
错误在于:
synchronized(static variable)
我构建代码的方式是这样的:
client.Send(mail);
错误是:
SmtpException:邮箱不可用。服务器响应是:不允许未经身份验证的发件人
答案 0 :(得分:1)
我设计了一个处理电子邮件的组件
首先将我的课程添加到您的项目中。
using System.ComponentModel;
using System.Net.Mail;
using System.Net;
using System.ComponentModel.DataAnnotations;
namespace Hector.Framework.Controls
{
public class MailMessageControl : Component
{
private MailMessage Mail = new MailMessage();
private SmtpClient SmtpClient = new SmtpClient();
public MailMessageControl()
{
Host = "smtp.gmail.com";
Port = 587;
EnableSSL = true;
}
public string Host
{
get => SmtpClient.Host;
set => SmtpClient.Host = value;
}
public int Port
{
get => SmtpClient.Port;
set => SmtpClient.Port = value;
}
public bool EnableSSL
{
get => SmtpClient.EnableSsl;
set => SmtpClient.EnableSsl = value;
}
public void AttachFile(string path)
{
Mail.Attachments.Add(new Attachment(path));
}
public void SetCredentials(string mail, string password)
{
SmtpClient.Credentials = new NetworkCredential(mail, password);
}
public void SetSender(string mail)
{
Mail.From = new MailAddress(mail);
}
public void AddAddressSee(string mail)
{
Mail.To.Add(mail);
}
public void SetSubject(string subject)
{
Mail.Subject = subject;
}
public void SetBody(string body, bool isHTML)
{
Mail.IsBodyHtml = isHTML;
Mail.Body = body;
}
public bool SendEmail()
{
try
{
SmtpClient.Send(Mail);
return true;
}
catch
{
return false;
}
}
public bool IsValidEmail(string email)
{
try
{
return new MailAddress(email).Address == email;
}
catch
{
return false;
}
}
public bool EmailIsValidated(string email)
{
return new EmailAddressAttribute().IsValid(email);
}
}
}
用法示例:
Hector.Framework.Controls.MailMessageControl mail = new Hector.Framework.Controls.MailMessageControl();
mail.SetCredentials("Your gmail email", "Your gmail password");
mail.SetSender("Sender mail");
mail.AttachFile("Your file path"); //If you want send file
mail.AddAddressSee("Add mail to receive your message");
mail.SetSubject("Subject");
mail.SetBody("Body", false);
if(mail.SendEmail())
{
//Mail send correctly
}
else
{
//Error
}
现在转到以下链接:https://myaccount.google.com/lesssecureapps
启用此开关:
这允许您的程序使用您的凭据发送电子邮件,如果您不激活它,可能会导致错误。
激活后,尝试发送消息
答案 1 :(得分:0)
你的代码对于匿名发送是'好'的,但你尝试发送的电子邮件服务器也希望你添加'发送'凭据。
通常,您会将SmtpClient配置保留在应用程序的.config文件中,并且代码中只会执行
SmtpClient client = new SmtpClient();
上面的行将从应用程序配置文件中读取配置 - 在用户配置下完全提供。同时为他提供输入SMTP凭据的选项。
以下是通过Gmail发送的示例:
<configuration>
<system.net>
<mailSettings>
<smtp from="Mail Displayname <xxxx.yyy@gmail.com>" deliveryMethod="Network">
<network host="smtp.gmail.com" enableSsl="true" port="587" password="password" userName="xxxx.yyy@gmail.com"></network>
</smtp>
</mailSettings>
</system.net>
</configuration>