For some reason, when trying to initialize the properties From, Subject, and Body for a MailMessage object I can't use variables from the method parameters.
Ex - Doesn't work:
public static void MailToEML(String email, String subj, String body)
{
MailMessage mailMessage = new MailMessage
{
From = new MailAddress(email),
Subject = subj,
Body = body
};
(Rest of method irrelevant)
Ex - Works
public static void MailToEML()
{
String email = "some#email.com";
String subj = "Subject";
String body = "Contents";
MailMessage mailMessage = new MailMessage
{
From = new MailAddress(email),
Subject = subj,
Body = body
};
I've tried with List<String>, String[], and String parameters, none of them seem to work, but when they are initialized inside the method, it works flawlessly.
Error when trying with parameters:
System.FormatException: 'The specified string is not in the form required for an e-mail address.'
FIXED: Similarily, if From is correct, Subject will output the same error message, and same with Body.
Solution: Appended a \n to Subject somewhere else in the code, which the formatting did not agree with, so I just had to remove that
Calling method:
public void ExportClicked(Office.IRibbonControl control)
{
Object selObject = Globals.ThisAddIn.Application.ActiveExplorer().Selection[1];
Outlook.MailItem mailItem =
(selObject as Outlook.MailItem);
String email;
String subject;
String body;
email = mailItem.SenderEmailAddress;
subject = mailItem.Subject;
body = mailItem.Body;
if (mailItem.Subject == null)
{
subject = ThisAddIn.lang[1]; //Array element determines language, not important here
}
ThisAddIn.MailToEML(email, subject, body);
}
(Just want to mention that I will be making these an array or list if I find a solution)
After searching around for a while, I figured out I was making this a lot more complicated than it really was. Instead of several string values, I used a MailItem object.
This is the new MailToEml() method:
public static void MailToEML(Outlook.MailItem mail)
{
MailMessage mailMessage = new MailMessage
{
From = new MailAddress(mail.SenderEmailAddress),
SubjectEncoding = System.Text.Encoding.UTF8,
Subject = mail.Subject,
Body = mail.Body
};
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.
This question already has answers here:
How to send HTML-formatted email? [duplicate]
(3 answers)
Closed 5 years ago.
I am calling a function that sends an email in my asp.net mvc project and I want the body to be able to format as html
Here is my function that sends the email :
private void EnvoieCourriel(string adrCourriel, string text, string object, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = object,
Body = text,
};
if (atache != null)
msg.Attachments.Add(atache);
msg.To.Add(adrCourriel);
smtp.Send(msg);
return;
}
The email is sent and it works like a charm, but It just shows plain html so I was wondering an argument in my instanciation of MailMessage
You just need to add the parameter IsBodyHtml to your instanciation of the MailMessage like this :
private bool EnvoieCourriel(string adrCourriel, string corps, string objet, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = objet,
Body = corps,
IsBodyHtml = true
};
if (atache != null)
msg.Attachments.Add(atache);
try
{
msg.To.Add(adrCourriel);
smtp.Send(msg);
}
catch(Exception e)
{
var erreur = e.Message;
return false;
}
return true;
}
I also added a try catch because if there is a problem when trying to send the message you can show an error or just know that the email was not sent without making the application crash
I think you are looking for IsBodyHtml.
private void EnvoieCourriel(string adrCourriel, string text, string object, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = object,
Body = text,
IsBodyHtml = true
};
if (atache != null)
msg.Attachments.Add(atache);
msg.To.Add(adrCourriel);
smtp.Send(msg);
return;
}
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 need to send a mail including the exception details (Yellow Screen Of Death) as attachment.
I could get the YSOD as follows:
string YSODmarkup = lastErrorWrapper.GetHtmlErrorMessage();
if (!string.IsNullOrEmpty(YSODmarkup))
{
Attachment YSOD = Attachment.CreateAttachmentFromString(YSODmarkup, "YSOD.htm");
mm.Attachments.Add(YSOD);
}
mm is of type MailMessage, but the mail is not sent.
Here
System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("from", "to", "Exception-Details", htmlEmail.ToString());
is used to bind the body of the mail.
After this only the attachment is added.
While removing the attachment, mail is sent.
Can anyone help me out?
As per the comments from Mr. Albin and Mr. Paul am updating the following
string YSODmarkup = Ex_Details.GetHtmlErrorMessage();
string p = System.IO.Directory.GetCurrentDirectory();
p = p + "\\trial.txt";
StreamWriter sw = new StreamWriter(p);
sw.WriteLine(YSODmarkup);
sw.Close();
Attachment a = new Attachment(p);
if (!string.IsNullOrEmpty(YSODmarkup))
{
Attachment YSOD = Attachment.CreateAttachmentFromString(YSODmarkup, "YSOD.html");
System.Net.Mail.Attachment(server.mappath("C:\\Documents and Settings\\user\\Desktop\\xml.docx"));
MyMailMessage.Attachments.Add(a);
}
Here i attached the contents to a text file and tried the same. So the mail was not sent. Is there any issue with sending mails which contains HTML tags in it. Because i was able to attach a normal text file.
namespace SendAttachmentMail
{
class Program
{
static void Main(string[] args)
{
var myAddress = new MailAddress("jhered#yahoo.com","James Peckham");
MailMessage message = new MailMessage(myAddress, myAddress);
message.Body = "Hello";
message.Attachments.Add(new Attachment(#"Test.txt"));
var client = new YahooMailClient();
client.Send(message);
}
}
public class YahooMailClient : SmtpClient
{
public YahooMailClient()
: base("smtp.mail.yahoo.com", 25)
{
Credentials = new YahooCredentials();
}
}
public class YahooCredentials : ICredentialsByHost
{
public NetworkCredential GetCredential(string host, int port, string authenticationType)
{
return new NetworkCredential("jhered#yahoo.com", "mypwd");
}
}
}
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"));