I have a website with an ASP.NET MVC backend running .NET 3.5. On this website, there is a script that sends emails using gmail as the mail service. The script runs and sends mail fine locally on my dev machine, but as soon as I upload it to the live server it fails. The only error message it is giving me at the moment is (since I told it to as you will see further down):
The transport failed to connect to the server.
Here is the code for the mailer script:
using System.Net.Mail;
using System.Web.Mail;
using MailMessage = System.Web.Mail.MailMessage;
namespace MySite.Helpers
{
public class GmailHelper
{
private readonly int _port = 465;
private readonly string _accountName;
private readonly string _password;
public GmailHelper(string accountName, string password)
{
_accountName = accountName;
_password = password;
}
public GmailHelper(string accountName, string password, int port)
{
_accountName = accountName;
_password = password;
_port = port;
}
public void Send(string from, string to, string subject, string body, bool isHtml)
{
Send(from, to, subject, body, isHtml, null);
}
public void Send(string from, string to, string subject, string body, bool isHtml, string[] attachments)
{
var mailMessage = new MailMessage
{
From = from,
To = to,
Subject = subject,
Body = body,
BodyFormat = isHtml ? MailFormat.Html : MailFormat.Text
};
// Add attachments
if (attachments != null)
{
foreach (var t in attachments)
{
mailMessage.Attachments.Add(new Attachment(t));
}
}
// Authenticate
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
// Username for gmail - email#domain.com for email for Google Apps
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _accountName);
// Password for gmail account
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _password);
// Google says to use 465 or 587. I don't get an answer on 587 and 465 works - YMMV
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _port.ToString());
// STARTTLS
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);
// assign outgoing gmail server
SmtpMail.SmtpServer = "smtp.gmail.com";
SmtpMail.Send(mailMessage);
}
}
}
And here is how it is called:
[HttpPost]
public ActionResult Employment(EmploymentModel model, FormCollection collection)
{
if (!ModelState.IsValid)
return View(model);
var results = new EmploymentViewModel();
try
{
results.Position = model.Position;
results.FirstName = model.FirstName;
results.LastName = model.LastName;
results.ContactPhone = model.ContactPhone;
results.OtherPhone = model.OtherPhone;
results.Address = model.Address;
results.Email = model.Email;
results.HsDiploma = model.HsDiploma.ToString();
results.CollegeYears = model.CollegeYears;
results.Skills = model.Skills;
results.Employment = model.Employment;
results.DateSent = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
var gmail = new GmailHelper("noreply#mysite.com", "[*removed*]");
var fromAddress = new MailAddress("noreply#mysite.com", "MySite");
var toAddress = new MailAddress("applications#mysite.com", "MySite Employment");
var subject = string.Format("Employment Application for {0} {1}", model.FirstName, model.LastName);
gmail.Send(fromAddress.Address, toAddress.Address, subject, EmployMailBody(results), false);
}
catch (Exception ex)
{
results.Sent = false;
results.Title = "Oops, our mail drone seems to have malfunctioned!";
results.Message = string.Format("We appologize, {0} {1}, but our email system has encountered an error and your email was not sent.</p>",
results.FirstName, results.LastName);
results.Message += Environment.NewLine + "<p>Please try your request later, or fax your résumé to our Corporate office.";
results.Message += Environment.NewLine + JQueryHelpers.GenerateErrorField(ex.Message);
return View("EmploymentSubmit", results);
}
results.Sent = true;
results.Title = "Thank you for your submission!";
results.Message = string.Format("Thank you for your interest in joining our team, {0} {1}!</p>", results.FirstName, results.LastName);
results.Message += Environment.NewLine + "<p>We have successfully recieved your information and will contact you shortly at the number your have provided.";
return View("EmploymentSubmit", results);
}
I am 99% positive that it was functional before when it was up on the site, but I could be mistaken as it has been a month or so since I have had to update the site.
Are there some additional steps I can take to debug this "better" to track down the underlying issue, or did I botch up my code somewhere accidentally?
Thanks!
EDIT1
So I updated the class to use strictly System.Net.Mail. I successfully sent a message from my dev machine. When I uploaded the site to my server, however, I got a new error message:
Request for the permission of type 'System.Net.Mail.SmtpPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
This site is hosted through godaddy.com, and some after searching around it seems godaddy only allows relaying through their smtp server. It looks like I'll have to change hosting providers to get this working properly.
Thanks!
EDIT2
The reason I moved to gmail from godaddy is originally when I had this script up the email would take anywhere from 15 to 45 minutes to arrive at the destination box. This could have been the deprecated code I was using before, but either way it is now being dispatched and arriving within seconds, as it should be. Here is my GoDaddy helper class, in case it will help someone:
public class GoDaddyHelperNet
{
private readonly int _port = 25;
private readonly MailAddress _accountName;
private readonly string _password;
private readonly string _host = "relay-hosting.secureserver.net";
public GoDaddyHelperNet(MailAddress accountName, string password)
{
_accountName = accountName;
_password = password;
}
public GoDaddyHelperNet(MailAddress accountName, string password, int port)
{
_accountName = accountName;
_password = password;
_port = port;
}
public GoDaddyHelperNet(MailAddress accountName, string password, int port, string host)
{
_accountName = accountName;
_password = password;
_port = port;
_host = host;
}
public void Send(MailAddress to, string subject, string body, bool isHtml)
{
Send(_accountName, to, subject, body, isHtml);
}
public void Send(MailAddress from, MailAddress to, string subject, string body, bool isHtml)
{
var smtp = new SmtpClient
{
Host = _host,
Port = _port,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(from.Address, _password),
Timeout = 15000
};
using (var message = new System.Net.Mail.MailMessage(from.Address, to.Address)
{
Subject = subject,
Body = body,
})
smtp.Send(message);
}
}
there is probably a firewall rule or other network device blocking you. verify that you can telnet to the gmail server from your web server and can send an email.
http://www.wikihow.com/Send-Email-Using-Telnet
if you can't you probably have to talk to your network admin. i have email problems like this on about half of my clients web servers.
Gmail has got lots of restrictions on SMTP relay. No more than 100 total recipients per day, IIRC. Limits on recipients per message as well. Limits on message/attachment size. If you exceed the limits or Gmail has decided that you look like a spam artiste, their SMTP server may well refuse the connection for a day or so.
Related
When i used this code, when the email is delivered the list of addresses in bcc is visible, why please?
I use .Net Framework 4.6.2
The code works correctly, it sends the emails but when I check the To: in the email delivered I can see all the recipients that I have included in .Bcc.Add
bcc does not work as microsoft says?
public static bool SendEmails(string[] emailList, string from, string body, string subject, string attachment)
{
var result= false;
MailMessage email = null;
if (emailList!= null && !string.IsNullOrWhiteSpace(from))
{
email = new MailMessage
{
Priority = MailPriority.High,
From = new MailAddress(from),
Subject = subject,
Body = body,
BodyEncoding = Encoding.UTF8,
IsBodyHtml = true,
DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure,
};
if (!string.IsNullOrWhiteSpace(attachment))
{
email.Attachments.Add(new Attachment(attachment));
}
var smtp = new SmtpClient
{
Host = host,
Credentials =new System.Net.NetworkCredential("user","pass"),
EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["enablessl"]),
Port = int.Parse(ConfigurationManager.AppSettings["port"])
};
if (emailList.Count() > 0)
{
foreach (string email in emailList)
{
email.Bcc.Add(new MailAddress(email));
}
}
smtp.Send(email);
result= true;
}
return restul;
}
Apparently, it is necessary to include an email in emai.To.Add("anymail#anyhost.com") before starting the loop where the addresses are loaded in bcc, I don't know if this has any other consequences, but that's how it works. Email addresses are no longer displayed in the To: of the delivered message.
I am using NetCore.MailKit NuGet package to help me send an email which contains a link to confirm their email when the user registers. I have followed the steps on their Github page but, I am getting an ArgumentNullException for the address, even though I have set the sending address.
The error:
ArgumentNullException: Value cannot be null. (Parameter 'address')
MimeKit.MailboxAddress..ctor(Encoding encoding, string name, string address)
The above error occurs when is send the email in my controller using IEmailService:
_EmailService.Send("usersemail#gmail.com", "subject", "message body");
This is my appsettings.json configuration:
"EmailConfiguration": {
"Server": "smtp.gmail.com",
"Port": 587,
"SenderName": "name",
"SenderEmail": "mygmail#gmail.com",
"SenderPassword": "My gmail password"
}
This is my setup in startup.cs
services.AddMailKit(optionBuilder =>
{
optionBuilder.UseMailKit(new MailKitOptions()
{
//get options from sercets.json
Server = Configuration["Server"],
Port = Convert.ToInt32(Configuration["Port"]),
SenderName = Configuration["SenderName"],
SenderEmail = Configuration["SenderEmail"],
Account = Configuration["SenderEmail"],
Password = Configuration["SenderPassword"],
Security = true
});
});
Below is the code for EmailService:
public void Send(string mailTo, string subject, string message, bool isHtml = false)
{
SendEmail(mailTo, null, null, subject, message, Encoding.UTF8, isHtml);
}
private void SendEmail(string mailTo, string mailCc, string mailBcc, string subject, string message, Encoding encoding, bool isHtml)
{
var _to = new string[0];
var _cc = new string[0];
var _bcc = new string[0];
if (!string.IsNullOrEmpty(mailTo))
_to = mailTo.Split(',').Select(x => x.Trim()).ToArray();
if (!string.IsNullOrEmpty(mailCc))
_cc = mailCc.Split(',').Select(x => x.Trim()).ToArray();
if (!string.IsNullOrEmpty(mailBcc))
_bcc = mailBcc.Split(',').Select(x => x.Trim()).ToArray();
Check.Argument.IsNotEmpty(_to, nameof(mailTo));
Check.Argument.IsNotEmpty(message, nameof(message));
var mimeMessage = new MimeMessage();
//add mail from
mimeMessage.From.Add(new MailboxAddress(_MailKitProvider.Options.SenderName, _MailKitProvider.Options.SenderEmail));
//add mail to
foreach (var to in _to)
{
mimeMessage.To.Add(MailboxAddress.Parse(to));
}
//add mail cc
foreach (var cc in _cc)
{
mimeMessage.Cc.Add(MailboxAddress.Parse(cc));
}
//add mail bcc
foreach (var bcc in _bcc)
{
mimeMessage.Bcc.Add(MailboxAddress.Parse(bcc));
}
//add subject
mimeMessage.Subject = subject;
//add email body
TextPart body = null;
if (isHtml)
{
body = new TextPart(TextFormat.Html);
}
else
{
body = new TextPart(TextFormat.Text);
}
//set email encoding
body.SetText(encoding, message);
//set email body
mimeMessage.Body = body;
using (var client = _MailKitProvider.SmtpClient)
{
client.Send(mimeMessage);
}
}
As you can see I have set everything, am I missing something here? why is address null at MimeKit.MailboxAddress()?
You seem to be not loading your configuration settings correctly. I suspect the failing line in your code is
//add mail from
mimeMessage.From.Add(new MailboxAddress(_MailKitProvider.Options.SenderName, _MailKitProvider.Options.SenderEmail));
The Options are all null, which causes the exception.
When you load the settings from a configuration file you need to prepend the section name to the variables. E.G.
services.AddMailKit(optionBuilder =>
{
optionBuilder.UseMailKit(new MailKitOptions()
{
//get options from sercets.json
Server = Configuration["EmailConfiguration:Server"],
Port = Convert.ToInt32(Configuration["EmailConfiguration:Port"]),
SenderName = Configuration["EmailConfiguration:SenderName"],
SenderEmail = Configuration["EmailConfiguration:SenderEmail"],
Account = Configuration["EmailConfiguration:SenderEmail"],
Password = Configuration["EmailConfiguration:SenderPassword"],
Security = true
});
});
My guess is that the exception is being thrown on the following line:
mimeMessage.From.Add(new MailboxAddress(_MailKitProvider.Options.SenderName, _MailKitProvider.Options.SenderEmail));
This means that _MailKitProvider.Options.SenderEmail is null.
I know you expect these values to be loaded correctly from your appsettings.json file, but seemingly, they are not being loaded for some reason.
I am trying to send e-mail from within a Xamarin Forms app, using Gmail.
I have created an Interface with only 1 method: SendEmail();
Then, in the Droid project, I added a class which implements said interface. Using the Dependency attribute and getting the implementation of the method in the main project, all is fine, except the following error:
Could not resolve host 'smtp.gmail.com'
This is the actual implementation of the method:
string subject = "subject here ";
string body= "body here ";
try
{
var mail = new MailMessage();
var smtpServer = new SmtpClient("smtp.gmail.com", 587);
mail.From = new MailAddress("myEmailAddress#gmail.com");
mail.To.Add("anotherAddress#yahoo.com");
mail.Subject = subject;
mail.Body = body;
smtpServer.Credentials = new NetworkCredential("username", "pass");
smtpServer.UseDefaultCredentials = false;
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
Searching around I could not find any details regarding it other that the actual smtp address.
Also, I have used the Less Secure apps procedure from Google, not receiving a credentials error I assume that it can connect to the account just fine.
Hello I have achieve this using the code below, also I have attached a file to the email, using the dependency service I use this methods:
Android:
public static string ICSPath
{
get
{
var path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, StaticData.CalendarFolderName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return Path.Combine(path, StaticData.CalendarFileName);
}
}
public async Task<bool> ShareCalendarEvent(List<ISegment> segmentList)
{
Intent choserIntent = new Intent(Intent.ActionSend);
//Create the calendar file to attach to the email
var str = await GlobalMethods.CreateCalendarStringFile(segmentList);
if (File.Exists(ICSPath))
{
File.Delete(ICSPath);
}
File.WriteAllText(ICSPath, str);
Java.IO.File filelocation = new Java.IO.File(ICSPath);
var path = Android.Net.Uri.FromFile(filelocation);
// set the type to 'email'
choserIntent.SetType("vnd.android.cursor.dir/email");
//String to[] = { "asd#gmail.com" };
//emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
choserIntent.PutExtra(Intent.ExtraStream, path);
// the mail subject
choserIntent.PutExtra(Intent.ExtraSubject, "Calendar event");
Forms.Context.StartActivity(Intent.CreateChooser(choserIntent, "Send Email"));
return true;
}
iOS:
public static string ICSPath
{
get
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), StaticData.CalendarFolderName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return Path.Combine(path, StaticData.CalendarFileName);
}
}
public async Task<bool> ShareCalendarEvent(List<ISegment> segmentList)
{
//Create the calendar file to attach to the email
var str = await GlobalMethods.CreateCalendarStringFile(segmentList);
if (File.Exists(ICSPath))
{
File.Delete(ICSPath);
}
File.WriteAllText(ICSPath, str);
MFMailComposeViewController mail;
if (MFMailComposeViewController.CanSendMail)
{
mail = new MFMailComposeViewController();
mail.SetSubject("Calendar Event");
//mail.SetMessageBody("this is a test", false);
NSData t_dat = NSData.FromFile(ICSPath);
string t_fname = Path.GetFileName(ICSPath);
mail.AddAttachmentData(t_dat, #"text/v-calendar", t_fname);
mail.Finished += (object s, MFComposeResultEventArgs args) =>
{
//Handle action once the email has been sent.
args.Controller.DismissViewController(true, null);
};
Device.BeginInvokeOnMainThread(() =>
{
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mail, true, null);
});
}
else
{
//Handle not being able to send email
await App.BasePageReference.DisplayAlert("Mail not supported",
StaticData.ServiceUnavailble, StaticData.OK);
}
return true;
}
I hope this helps.
Figured it own finally!
First of all, I was using Android Player by Xamarin, which apparently does not support network connectivity.
So my fix was easy: used an Android Emulator ( any version of it for that matter ) built in Visual Studio Community 2015, and tested network connectivity using the plugin by James Montemagno ( Xam.Plugin.Connectivity on NuGet ).
I have an ASP.Net web application that's been tested extensively. One portion of it sends an email automatically using System.Net.Mail.SmtpClient. During testing, from various Windows 7 machines, the emails were sent and were formatted with a reasonable font size. I don't set the font size in the code, BTW. Now that the application's in production, the first email got sent in a very small font and the users want the font size increased. I can hard-code the font size of course, but I'd prefer to understand what's going on here. What determines the font size? Is it something in the SmtpClient, or some setting on the SMTP server, or what? Below is the code that sends the email. TemplateEditor is an AjaxControlToolkit.HTMLEditor control on the page. AttyParaMessageBody is the variable that contains the email body. Our users are on Windows 7 with Outlook 2010.
string AttyParaMessageBody = TemplateEditor.Content;
LHEmail.SendEmail(LHClassLibrary.LHConfigurationManager.AppSettings["ApprovedNewVersionLHEmailSubject"].ToString(), AttyParaMessageBody, AttyParaAddressees, CurrentLitHoldDetails.ResponsibleAttorney.Email, LHClassLibrary.LHConfigurationManager.AppSettings["EmailCCList"].ToString() + ";" + tbEmails.Text);
public static void SendEmail(string subject, string body, string to, string from, string cc)
{
SendEmail(subject, body, to, from, cc, "", "", MailPriority.High);
}
public static void SendEmail(string subject, string body, string to, string from, string cc, string bcc, string fileName, MailPriority Priority)
{
MailMessage msgMail = new MailMessage();
SmtpClient emailClient = new SmtpClient();
try
{
msgMail = BuildMessage(subject, body, to, cc, bcc, from, fileName, Priority);
emailClient.Send(msgMail);
}
catch (Exception ex)
{
string exception = ex.ToString();
}
finally
{
msgMail.Dispose();
}
}
private static MailMessage BuildMessage(string subject, string body, string to, string cc, string bcc, string from, string fileName, MailPriority Priority)
{
MailMessage msgMail = new MailMessage();
if (!to.Equals(string.Empty))
{
//format emails for .NET 4.0 version
string[] toAddressList = to.Split(';');
//Loads the To address field
foreach (string toaddress in toAddressList)
{
if (toaddress.Length > 0)
{
msgMail.To.Add(toaddress);
}
}
//optional args
//format emails for .NET 4.0 version
if (!cc.Equals(string.Empty))
{
string[] ccAddressList = cc.Split(';');
//Loads the Cc address field
foreach (string ccaddress in ccAddressList)
{
if (ccaddress.Length > 0)
{
msgMail.CC.Add(ccaddress);
}
}
}
if (!bcc.Equals(string.Empty))
{
string[] bccAddressList = bcc.Split(';');
//Loads the Bcc address field
foreach (string bccaddress in bccAddressList)
{
if (bccaddress.Length > 0)
{
msgMail.Bcc.Add(bccaddress);
}
}
}
if (!fileName.Equals(string.Empty))
msgMail.Attachments.Add(new Attachment(fileName));
msgMail.Priority = Priority;
msgMail.From = ((from == null) || (from.Equals(string.Empty))) ? new MailAddress("LitHold#kramerlevin.com", "Litigation Hold") : new MailAddress(from, "Litigation Hold");
msgMail.Subject = subject;
msgMail.Body = body;
msgMail.IsBodyHtml = true;
}
else { throw new SmtpFailedRecipientException("Failed to provide destination address"); }
return msgMail;
}
From my experience, when i need to format my e-mail content that will be sent through SMTP, i will use HTML tag when i set value for the content variable. For example:
String content = "<h2>Thank you for your e-mail</h2><font size=4>We appreciate your feedback.<br/> We will process your request soon</font><br/>Regards.";
If ur content will be set in the code behind, then u can using the above method.
Hope it helps.
I'm going through my app, trying to clean up some code that sends e-mails. I started creating my own emailer wrapper class, but then I figured that there must be a standard emailer class out there somewhere. I've done some searching, but couldn't find anything.
Also, is there a code base for stuff like this anywhere?
EDIT: Sorry, let me clarify.
I don't want to have this in my code any time I need to send an e-mail:
System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage();
message.From="from e-mail";
message.To="to e-mail";
message.Subject="Message Subject";
message.Body="Message Body";
System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address";
System.Web.Mail.SmtpMail.Send(message);
I created a class named Emailer, that contains functions like:
SendEmail(string to, string from, string body)
SendEmail(string to, string from, string body, bool isHtml)
And so I can just put this a single line in my code to send an e-mail:
Emailer.SendEmail("name#site.com", "name2#site.com", "My e-mail", false);
I mean, it's not too complex, but I figured there was a standard, accepted solution out there.
Something like this?
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using MailMessage=System.Net.Mail.MailMessage;
class CTEmailSender
{
string MailSmtpHost { get; set; }
int MailSmtpPort { get; set; }
string MailSmtpUsername { get; set; }
string MailSmtpPassword { get; set; }
string MailFrom { get; set; }
public bool SendEmail(string to, string subject, string body)
{
MailMessage mail = new MailMessage(MailFrom, to, subject, body);
var alternameView = AlternateView.CreateAlternateViewFromString(body, new ContentType("text/html"));
mail.AlternateViews.Add(alternameView);
var smtpClient = new SmtpClient(MailSmtpHost, MailSmtpPort);
smtpClient.Credentials = new NetworkCredential(MailSmtpUsername, MailSmtpPassword);
try
{
smtpClient.Send(mail);
}
catch (Exception e)
{
//Log error here
return false;
}
return true;
}
}
Maybe you're looking for SmtpClient?
I use a generic class made out of this old Stack Overflow Answer.
Try this.
public bool SendEmail(MailAddress toAddress, string subject, string body)
{
MailAddress fromAddress = new MailAddress("pull from db or web.config", "pull from db or web.config");
string fromPassword = "pull from db or config and decrypt";
string smtpHost = "pull from db or web.config";
int smtpPort = 587;//gmail port
try
{
var smtp = new SmtpClient
{
Host = smtpHost,
Port = smtpPort,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
smtp.Send(message);
}
return true;
}
catch (Exception err)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(err);
return false;
}
}
This is a snippet from one of my projects. It's a little more feature-packed than some of the other implementations.
Using this function allows you to create an email with:
Tokens that can be replaced with actual values at runtime
Emails that contain both a text and HTML view
public MailMessage createMailMessage(string toAddress, string fromAddress, string subject, string template)
{
// Validate arguments here...
// If your template contains any of the following {tokens}
// they will be replaced with the values you set here.
var replacementDictionary = new ListDictionary
{
// Replace with your own list of values
{ "{first}", "Pull from db or config" },
{ "{last}", "Pull from db or config" }
};
// Create a text view and HTML view (both will be in the same email)
// This snippet assumes you are using ASP.NET (works w/MVC)
// if not, replace HostingEnvironment.MapPath with your own path.
var mailDefinition = new MailDefinition { BodyFileName = HostingEnvironment.MapPath(template + ".txt"), IsBodyHtml = false };
var htmlMailDefinition = new MailDefinition { BodyFileName = HostingEnvironment.MapPath(template + ".htm"), IsBodyHtml = true };
MailMessage htmlMessage = htmlMailDefinition.CreateMailMessage(email, replacementDictionary, new Control());
MailMessage textMessage = mailDefinition.CreateMailMessage(email, replacementDictionary, new Control());
AlternateView plainView = AlternateView.CreateAlternateViewFromString(textMessage.Body, null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlMessage.Body, null, "text/html");
var message = new MailMessage { From = new MailAddress(from) };
message.To.Add(new MailAddress(toAddress));
message.Subject = subject;
message.AlternateViews.Add(plainView);
message.AlternateViews.Add(htmlView);
return message;
}
Assuming you have your Web.config set up for NetMail, you can call this method from a helper method like so:
public bool SendEmail(MailMessage email)
{
var client = new SmtpClient();
try
{
client.Send(message);
}
catch (Exception e)
{
return false;
}
return true;
}
SendMail(createMailMessage("to#email.com", "from#email.com", "Subject", "~/Path/Template"));