1

I was trying to create a function that emails to target address when used.

my email model:

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; }
    }
}

my controller:

/// <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);
}

how i use it :

        // 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);

In my web project create a report as excel file and wanna send it to my self attached to an email. I'm not sure what's wrong or what i am missing here.. Everything seems valid to me but still i get this error :

MY ERROR IMAGE

Stack Trace:

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: 

so what am i missing here? whats wrong? how can i solve this issue?

Berker Yüceer
  • 7,026
  • 18
  • 68
  • 102
  • 3
    Your mail server is refusing to send the message. This may indicate a bad password. – SLaks Nov 21 '12 at 14:32
  • This isn't necessarily a programming question. It's more likely a configuration/replay permission issue on the server. It might be a better fit at ServerFault.com We see this sometimes in oiur shop when a new SMTP server is set up because it's locked down by default. We have to explicitly allow certain users/servers to relay SMTP messages through our SMTP Servers. – David Nov 21 '12 at 14:35
  • but my password is totaly fine and im trying to mail programatically so question fits here. – Berker Yüceer Nov 21 '12 at 14:36
  • http://serverfault.com/questions/238095/mailbox-unavailable-client-does-not-have-permissions-to-send-as-this-sender-o – David Nov 21 '12 at 14:38
  • Just because the mail is being sent pragmatically doesn't mean it fits here. if the problem is at the server and the fix is to configure it correctly, it's in your best interest to go to the community with the experts in that area of I.T. I'm not trying to be mean, but rather helpful. The link I posted above to ServerFault.com above describes the configuration issue that I suspect is the problem. – David Nov 21 '12 at 14:40
  • @DavidStratton problem is i didnt know the meaning of this error and im trying to create a .net mailer for my self programatically for that reason i showed all my model + code to see if im missing something and also the on the link you gave they can send mails already but they are having that error every second mail which looks more like a "serverfault" issue. In my issue i cant even send a mail so what you suggest doesnt really make sense in my part. I understand you wanted to help but doesnt solves my issue. Thank you anyway for your efforts. – Berker Yüceer Nov 21 '12 at 14:49

1 Answers1

1

You can use following code:

    /// <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();
    }

And this is how you should use it for 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);
Gregor Primar
  • 6,759
  • 2
  • 33
  • 46
  • hope adding an attachment doesnt blows this. – Berker Yüceer Nov 21 '12 at 14:44
  • Try it. This code works 100% I use it every day. If you will have any kind of error then you should look at your server/domain configuration. – Gregor Primar Nov 21 '12 at 14:46
  • As i was sure of it your code worked perfectly i also added attachment after `message.Priority = priority;`. Thanks for the solution. This code also a proof of DavidStratton kinda mistaken about this problem. It caused by dirty coding not the server. I'm not saying this to be mean about him. I'm just trying to shoo off misleadings. – Berker Yüceer Nov 21 '12 at 15:23