1

我试图创建一个在使用时通过电子邮件发送到目标地址的功能。

我的电子邮件模型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Mail;
using System.Security;

namespace myspecial.net.Models
{
    public class EmailModel
    {
        // Sender email and recipient email
        public MailAddress Sender { get; set; }
        public IEnumerable<MailAddress> Recipient { get; set; }
        // Subject and message
        public String Subject { get; set; }
        public String Body { get; set; }
        // Attachment Files
        public String AttachmentPath { get; set; }
        // Login Information
        public String UserName { get; set; }
        public String Password { get; set; }
        // Simple Mail Transfer Protocol (SMTP) provider and port
        public String SmtpServer { get; set; }
        public Int32 SMTPport { get; set; }
        // Post Office Protocol (POP) version 3 provider and port
        public String POP3Server { get; set; }
        public Int32 POP3port { get; set; }
        // Secure Sockets Layer
        public Boolean SSL { get; set; }
    }
}

我的控制器:

/// <summary>
/// E-Mail's to the address. Before using this function fill the email model.
/// </summary>
public void Email(EmailModel mailer)
{
    MailMessage mail = new MailMessage();
    // Standart required mail information
    mail.From = mailer.Sender;
    mail.Sender = mailer.Sender;
    // Recipients
    foreach (MailAddress rcpnt in mailer.Recipient.ToList())
    { mail.To.Add(rcpnt); }
    // Subject
    mail.Subject = mailer.Subject;
    // Body
    mail.Body = mailer.Body;
    // Optional Attachment
    if (mailer.AttachmentPath != null || mailer.AttachmentPath.Trim() != "")
    {
        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment(mailer.AttachmentPath.Trim());
        mail.Attachments.Add(attachment);
    }
    // Important (Simple Mail Transfer Protocol)
    SmtpClient SmtpServer = new SmtpClient(mailer.SmtpServer,mailer.SMTPport);
    SmtpServer.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; 
    SmtpServer.Credentials = new System.Net.NetworkCredential(mailer.UserName, mailer.Password, mailer.SmtpServer);
    SmtpServer.Port = mailer.SMTPport;
    SmtpServer.EnableSsl = mailer.SSL;
    ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
    // Send Mail
    SmtpServer.Send(mail);
}

我如何使用它:

        // Send as mail
        EmailModel mail = new EmailModel();
        // Mail addresses to send
        MailAddress[] addressler = new MailAddress[] { new MailAddress("berkeryuceer@yahoo.com") };
        // Options here
        mail.SMTPport = 465; // Port // 465 // 26 // 25 // 366 // 587
        mail.SmtpServer = "smtp.gmail.com"; // Server
        mail.UserName = "MyGmailAddress@gmail.com"; // UserName
        mail.Password = "**********"; // Password 
        mail.SSL = true; // Secure Sockets Layer
        // Mail
        mail.Sender = new MailAddress("MyGmailAddress@gmail.com"); // Sender (From)
        mail.Recipient = addressler; // Recipient (To)
        mail.Subject = "Some subject here..";
        mail.Body = "Some blabla bla blablabla blabla here...";
        // Optional Attachment // Attach excel file. 
        mail.AttachmentPath = ExportToExcelForMail(id).ToString(); 
        Email(mail);

在我的网络项目中,创建一个作为 excel 文件的报告,并希望将其发送给我自己附加到电子邮件中。我不确定有什么问题或我在这里遗漏了什么.. 一切对我来说似乎都是有效的,但我仍然收到这个错误:

我的错误图片

堆栈跟踪:

System.Net.Mail.SmtpFailedRecipientException was unhandled by user code
  Message=Posta kutusu kullanılamıyor. Sunucu yanıtı şöyleydi: 5.7.1 <MyGmailAddress@gmail.com> Access to <berkeryuceer@yahoo.com> not allowed
  Source=System
  FailedRecipient=<berkeryuceer@yahoo.com>
  StackTrace:
       konum: System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
       konum: System.Net.Mail.SmtpClient.Send(MailMessage message)
       konum: blabla.net.Controllers.OtelFormsController.Email(EmailModel mailer) D:\bla\bla\blabla.net\blabla.net\Controllers\OtelFormsController.cs içinde: satır 753
       konum: blabla.net.Controllers.OtelFormsController.Close(Int32 id) D:\bla\bla\blabla.net\blabla.net\Controllers\OtelFormsController.cs içinde: satır 691
       konum: lambda_method(Closure , ControllerBase , Object[] )
       konum: System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       konum: System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       konum: System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       konum: System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
       konum: System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  InnerException: 

所以我在这里想念什么?怎么了?我该如何解决这个问题?

4

1 回答 1

1

您可以使用以下代码:

    /// <summary>
    /// Sends mail with authentification
    /// </summary>
    /// <param name="recipients"></param>
    /// <param name="from"></param>
    /// <param name="subject"></param>
    /// <param name="body"></param>
    /// <param name="isHTMLbody"></param>
    /// <param name="SMTPhost"></param>
    /// <param name="priority"></param>
    /// <param name="credentials"></param>
    /// <param name="port"></param>
    /// <param name="enableSsl"></param>
    static void SendMailWithAuthentication(List<string> recipients, string from, string subject, string body, bool isHTMLbody,
        string SMTPhost, System.Net.Mail.MailPriority priority, System.Net.NetworkCredential credentials, int? port, bool enableSsl)
    {
        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
        foreach (string recipient in recipients)
        {
            message.To.Add(recipient);
        }
        message.SubjectEncoding = Encoding.UTF8;
        message.BodyEncoding = Encoding.UTF8;
        message.Subject = subject;
        message.From = new System.Net.Mail.MailAddress(from);
        message.IsBodyHtml = isHTMLbody;
        message.Body = body;
        message.Priority = priority;
        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        client.Credentials = credentials;
        client.Host = SMTPhost;
        if (port != null)
        {
            client.Port = (int)port;
        }
        client.EnableSsl = enableSsl;
        client.Send(message);
        message.Dispose();
    }

这就是你应该如何将它用于 gmail:

        string subject = "my subject";
        string body = "my html body";
        int port = 587;
        string SMTPhost = "smtp.gmail.com";
        string sender = "my@email.com";
        System.Net.Mail.MailPriority mPriority = System.Net.Mail.MailPriority.Low;        
        List<string> recipients = new List<string>(){"some@reciever.com"};
        bool enableSSL = true;
        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("UserName","Password");
        SendMailWithAuthentication(recipients, sender, subject, body, true,
            SMTPhost,
            mPriority, credentials,
            enableSSL);
于 2012-11-21T14:41:39.647 回答