Solved

Replacing SMTP in my page

Posted on 2016-09-15
12
46 Views
Last Modified: 2016-09-26
Hi,

I have an simple MVC app that is currently sending email using SMTP.

I have now migrated the app to Azure and the SMTP no longer works.  

I have to use SendGrid now but I am not sure how I need to change the code in order to use the new SendGrid method.  I don't want to have to re-write my entire current email page if its unessarsary.

Here is the guide I'm using:

https://azure.microsoft.com/en-gb/documentation/articles/sendgrid-dotnet-how-to-send-email/

I completed up until the code part.

Here's my current email.cs page in its entirety..


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using SendGrid;



namespace smashandgrab
{
    public class EmailSender
    {
        string EmailSenderId = WebConfigurationManager.AppSettings["EmailSenderId"];
        string EmailSenderPassword = WebConfigurationManager.AppSettings["EmailSenderPassword"];
        string EmailSenderEnableSsl = WebConfigurationManager.AppSettings["EmailSenderEnableSsl"];
        string EmailSenderHost = WebConfigurationManager.AppSettings["EmailSenderHost"];
        string EmailSenderPort = WebConfigurationManager.AppSettings["EmailSenderPort"];
        string SenderTitle = WebConfigurationManager.AppSettings["SenderTitle"];
        string emailBody = "";






        public void SendEmail(DataResult obj)
        {
            string path = HttpContext.Current.Server.MapPath("/EmailFormat/EstimationEmail.html");

            if (File.Exists(path))
            {
                emailBody = File.ReadAllText(path);
                emailBody = emailBody.Replace("#FloorDepth#", obj.FloorDepth);
                emailBody = emailBody.Replace("#val220#", obj.val220);
                emailBody = emailBody.Replace("#val240#", obj.val240);
                emailBody = emailBody.Replace("#val300#", obj.val300);
                emailBody = emailBody.Replace("#Include1#", obj.Include1);
                emailBody = emailBody.Replace("#Include2#", obj.Include2);
                emailBody = emailBody.Replace("#Include3#", obj.Include3);
                emailBody = emailBody.Replace("#Include4#", obj.Include4);
                emailBody = emailBody.Replace("#Include5#", obj.Include5);
                emailBody = emailBody.Replace("#Include6#", obj.Include6);
                emailBody = emailBody.Replace("#Include7#", obj.Include7);
                emailBody = emailBody.Replace("#Include8#", obj.Include8);
                emailBody = emailBody.Replace("#Include9#", obj.Include9);
                emailBody = emailBody.Replace("#Include10#", obj.Include10);

            }

            using (MailMessage mail = new MailMessage())
            {
                mail.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnSuccess;
                mail.From = new MailAddress(EmailSenderId);
                mail.To.Add(obj.Email);
                mail.Subject = "Quote";
                mail.Body = emailBody;
                mail.IsBodyHtml = true;  
                MailAddress mailaddress = new MailAddress(EmailSenderId, SenderTitle);
                mail.From = mailaddress;
                using (SmtpClient smtp = new SmtpClient(EmailSenderHost, Convert.ToInt32(EmailSenderPort)))
                {
                    smtp.Credentials = new NetworkCredential(EmailSenderId, EmailSenderPassword);
                    smtp.EnableSsl = Convert.ToBoolean(EmailSenderEnableSsl);
                    smtp.Send(mail);
                }
            }
        }
    }
}

Open in new window


Really hoping that someone can help with this :)
0
Comment
Question by:SmashAndGrab
  • 7
  • 5
12 Comments
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 41805290
code looks ok.. Are you getting any error?

do u have the correct smptp address/port


This is wht send grid uses:

host:smtp.sendgrid.net
port:587

it would be better if you use their api's for sending emails, then you can track the emails as well whether it was delivered correctly and so on
0
 

Author Comment

by:SmashAndGrab
ID: 41806087
Hi Gautham,

Thank for the advice :)

I am trying to use the sendgrid API but am having some problems.

I am using this guide:

https://azure.microsoft.com/en-gb/documentation/articles/sendgrid-dotnet-how-to-send-email/


I've followed the guide perfectly but I get the errors:

Error

I think I've just got myself in a muddle with my old smtp code and the new sendgrid code :(

here is the code in my email.cs file:

The old SMTP method is commented at the bottom.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using SendGrid;



namespace smashandgrab
{
    public class EmailSender
    {
        string EmailSenderId = WebConfigurationManager.AppSettings["EmailSenderId"];
        string EmailSenderPassword = WebConfigurationManager.AppSettings["EmailSenderPassword"];
        string EmailSenderEnableSsl = WebConfigurationManager.AppSettings["EmailSenderEnableSsl"];
        string EmailSenderHost = WebConfigurationManager.AppSettings["EmailSenderHost"];
        string EmailSenderPort = WebConfigurationManager.AppSettings["EmailSenderPort"];
        string SenderTitle = WebConfigurationManager.AppSettings["SenderTitle"];
        string emailBody = "";






        public void SendEmail(DataResult obj)
        {
            string path = HttpContext.Current.Server.MapPath("/EmailFormat/EstimationEmail.html");





            if (File.Exists(path))
            {
                emailBody = File.ReadAllText(path);
                emailBody = emailBody.Replace("#FloorDepth#", obj.FloorDepth);
                emailBody = emailBody.Replace("#val220#", obj.val220);
                emailBody = emailBody.Replace("#val240#", obj.val240);
                emailBody = emailBody.Replace("#val300#", obj.val300);
                emailBody = emailBody.Replace("#Include1#", obj.Include1);
                emailBody = emailBody.Replace("#Include2#", obj.Include2);
                emailBody = emailBody.Replace("#Include3#", obj.Include3);
                emailBody = emailBody.Replace("#Include4#", obj.Include4);
                emailBody = emailBody.Replace("#Include5#", obj.Include5);
                emailBody = emailBody.Replace("#Include6#", obj.Include6);
                emailBody = emailBody.Replace("#Include7#", obj.Include7);
                emailBody = emailBody.Replace("#Include8#", obj.Include8);
                emailBody = emailBody.Replace("#Include9#", obj.Include9);
                emailBody = emailBody.Replace("#Include10#", obj.Include10);

            }
            //api credentials
            var username = System.Environment.GetEnvironmentVariable("SENDGRID_USER");
            var pswd = System.Environment.GetEnvironmentVariable("SENDGRID_PASS");
            var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");

            // Create the email object first, then add the properties.
            SendGrid.SendGridAPIClient = new SendGridAPIClient("", "");
            //  .SendGridMessage myMessage = new SendGridMessage();

            

           
            myMessage.AddTo(obj.Email);
            myMessage.From = new MailAddress(EmailSenderId, SenderTitle);
            myMessage.Subject = "Quote";
            myMessage.Text = emailBody;

            // Create credentials, specifying your user name and password.
            var credentials = new NetworkCredential(EmailSenderId, EmailSenderPassword);

            // Create an Web transport for sending email.
            var transportWeb = new Web(credentials);

            // Send the email, which returns an awaitable task.
            transportWeb.DeliverAsync(myMessage);

            // If developing a Console Application, use the following
            // transportWeb.DeliverAsync(mail).Wait();

            //using (MailMessage mail = new MailMessage())
            //{
            //    mail.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnSuccess;
            //    mail.From = new MailAddress(EmailSenderId);
            //    mail.To.Add(obj.Email);
            //    mail.Subject = "Quote";
            //    mail.Body = emailBody;
            //    mail.IsBodyHtml = true;  
            //    MailAddress mailaddress = new MailAddress(EmailSenderId, SenderTitle);
            //    mail.From = mailaddress;
            //    using (SmtpClient smtp = new SmtpClient(EmailSenderHost, Convert.ToInt32(EmailSenderPort)))
            //    {
            //        smtp.Credentials = new NetworkCredential(EmailSenderId, EmailSenderPassword);
            //        smtp.EnableSsl = Convert.ToBoolean(EmailSenderEnableSsl);
            //        smtp.Send(mail);
            //    }
            //}
        }
    }
}

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 41806309
this is how i did in one of my apps

public static bool SendEmail(string toList, string subject, string body, string fromAddress, string fromName, string apiKey)
        {
            try
            {
                SendGridMessage myMessage = new SendGridMessage();
                myMessage.AddTo(toList);
                myMessage.From = new MailAddress(fromAddress, fromName);
                myMessage.Subject = subject;

                myMessage.Html = body;
                var transportWeb = new Web(apiKey);
                var task = transportWeb.DeliverAsync(myMessage);
                task.Wait();
                return task.IsCompleted;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Open in new window

1
 

Author Comment

by:SmashAndGrab
ID: 41808533
Hi,

I've tried yours but I have a simular issue:

simular issue
0
 

Author Comment

by:SmashAndGrab
ID: 41808535
the code I used..
0
 

Author Comment

by:SmashAndGrab
ID: 41808536
I dont really understand it.. I have used the sendgrid references (as you can see highlighted above)
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 41808618
can you try adding these two nuget packages

Sendgrid.6.3.4
SendGrid.SmtpApi.1.3.1
0
 

Author Comment

by:SmashAndGrab
ID: 41808762
I went a bit nuts and installed all of these..

Currently installed
My framework is: 4.5.2
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 41808785
still same error?
0
 

Author Comment

by:SmashAndGrab
ID: 41808789
Yes.

"the type or namespace 'SendGridMessage' ....


What is annoying is that its my only option for sending emails using Azure!  Even MS support can't help me!

Frustrating !
0
 
LVL 29

Accepted Solution

by:
Gautham Janardhan earned 500 total points
ID: 41808809
can you try exploring this dll "SendGridMail.dll" and see if you can find this class?

Only thing different is that you are on a higher version than mine (urs is 8 and mine is 6)
0
 

Author Comment

by:SmashAndGrab
ID: 41816169
I found it thanks to you!  

I was using the wrong version of sendgrid.   I downgraded my version to 6.2.4 and now the SendGridMail is available.

Thank you for all your help.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now