could not send a mail using SMTP server and AJAX

452 views Asked by At

I'm new to asp.net MVC. I'm trying to send a mail with attachment using SMTP server and AJAX in asp.net MVC. The mail could not be sent.

HomeController.cs

public JsonResult SendMailToUser()
    {
        bool result = false;
        result = SendEmail("Receiver_mail", "Test", "<p>Hi abc,<br/>This message is for testing purpose. So don't be upset.<br/>Kind Regards,<br/>abc</p>");
        return Json(result, JsonRequestBehavior.AllowGet);
    }
    public bool SendEmail(string toEmail, string subject, string emailBody)
    {
        try
        {
            string senderEmail = System.Configuration.ConfigurationManager.AppSettings["Sender_Mail.com"].ToString();
            string senderPassword = System.Configuration.ConfigurationManager.AppSettings["Outlook@123"].ToString();

            SmtpClient client = new SmtpClient("smtp-mail.outlook.com", 587);
            client.EnableSsl = false;
            client.Timeout = 100000;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(senderEmail, senderPassword);

            MailMessage mailMessage = new MailMessage(senderEmail, toEmail, subject, emailBody);
            mailMessage.IsBodyHtml = true;
            mailMessage.BodyEncoding = UTF8Encoding.UTF8;

            client.Send(mailMessage);

            return true;
        }
        catch (Exception ex)
        {
            return false;
        }

    }

Layout.cshtml

<button type="submit" id ="export" onclick="SendEmail()" class="Layoutbuttons" style="vertical-align:middle"><span>get report via mail</span></button>

<script>
var SendEmail = function () {
    $.ajax({
        type: "Post",
        url: "/Home/SendMailToUser",
        success: function (data) {
            alert("Success");
        }
    })
}
</script>

Web.config

<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="SenderEmail" value="Sender_Mail" />
<add key="SenderPassword" value="Outlook@123" />
</appSettings>

Is there anything that need to be done in Outlook 2007 settings? The outlook 2007 runs on Exchange server.

1

There are 1 answers

0
Nelson Kingsley On

Thanks for all the suggestions! I found the following solution. It works in localhost perfectly but fails after publishing! Kindly suggest a way out!

HomeController.cs

    public static Microsoft.Office.Interop.Outlook.Application GetActiveOutlookApplication()
    {
        return (Microsoft.Office.Interop.Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
    }

    public void SendMailToUser()
    {
        try
        {
            Outlook.Application app = new Outlook.Application();
            Outlook.MailItem mail = app.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
            mail.Subject = "Test mail";
            mail.Body = "Test";

            Outlook.AddressEntry currentUser = app.Session.CurrentUser.AddressEntry;
            if (currentUser.Type == "EX")
            {
                Outlook.ExchangeUser user = currentUser.GetExchangeUser();
                // Add recipient using display name, alias, or smtp address
                mail.Recipients.Add(user.PrimarySmtpAddress);
                mail.Recipients.ResolveAll();
                mail.Attachments.Add(@"URL", Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                mail.Send();
            }
        }
        catch (Exception ex)
        {

        }
    }

Layout.cshtml

<button type="submit" id ="export" onclick="SendEmail()" class="Layoutbuttons" style="vertical-align:middle"><span>Get report via mail</span></button>



<script>
var SendEmail = function () {
    $.ajax({
        type: "Post",
        url: '@Url.Action("SendMailToUser", "Home")',
        success: function () {
            alert("Mail sent successfully!");
        }
    })
}
</script>