I below code is to send email by reading the template html, and it works fine. But now my question is how to pass Salutation customerName from my .net code to the template at run time.
StringBuilder strBlr = new StringBuilder();
string strHTML = string.Empty;
string strTempalteHtmlpath = string.Empty;
//create the mail message
MailMessage mail;
string strFrom = ConfigurationSettings.AppSettings["fromAddressForBT"];
string strSubject = "Thanks for choosing Email contact preference";
mail = new MailMessage(strFrom, customerDetails.EmailId);
mail.Subject = strSubject;
//Read Html Template File Path
strTempalteHtmlpath = Convert.ToString(ConfigurationSettings.AppSettings["TemplatePath"]);
strHTML = File.ReadAllText(strTempalteHtmlpath);
strBlr = strBlr.Append(strHTML);
mail.Body = strBlr.ToString();
mail.IsBodyHtml = true;
//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString(strBlr.ToString(), null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(strBlr.ToString(), null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
//send the message
SmtpClient smtpMail = new SmtpClient(ConfigurationSettings.AppSettings["smtpClient"]);
smtpMail.Send(mail);
mail.Dispose();
Thanks.
This is code for sendemail button
StreamReader sr = new StreamReader(Server.MapPath("Sendpage.htm"));
string body = sr.ReadToEnd();
sr.Close();
body = body.Replace("#NameFamily#", txtNameFamily.Text);
body = body.Replace("#Email#", txtEmail.Text);
body = body.Replace("#Tellphone#", txtTellphone.Text);
body = body.Replace("#Text#", txtText.Text);
body = body.Replace("#Date#", DateTime.Now);
string Time = Convert.ToString(DateTime.Now.ToShortTimeString());
body = body.Replace("#Time#", Time);
SendMail("email that you want to send to it", body);
this is sendmail function code:
private void SendMail(string To, string Body)
{
SmtpClient Mailing = new SmtpClient("mail.domain.com");
MailMessage Message = new MailMessage();
Message.From = new MailAddress("mail#domain.com", "Your name or company name");
Message.Subject = "Subject";
Message.SubjectEncoding = Encoding.UTF8;
Message.IsBodyHtml = true;
Message.BodyEncoding = Encoding.UTF8;
Message.Body = Body;
Message.To.Add(new MailAddress(To));
Mailing.UseDefaultCredentials = false;
NetworkCredential MyCredential = new NetworkCredential("mail#domain.com", "password");
Mailing.Credentials = MyCredential; Mailing.Send(Message);
}
Related
I want to automate my work by sending the screenshot taken during automation in tabular email format . I had successfully attached as document, but I want it in tabular format. This is code what I had already tried
public static void email_send() {
string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:test1.jpeg\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource("test1.jpeg", MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
avHtml.LinkedResources.Add(inline);
Attachment att = new Attachment(#"D:/test123.png");
att.ContentDisposition.Inline = true;
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(avHtml);
System.Net.Mail.SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("*****");
mail.To.Add("*******");
mail.Subject = "Test Mail - 1";
mail.Body = String.Format(
"<h3>Client: " + " Has Sent You A Screenshot</h3>" +
#"<img src=""cid:{0}"" />", inline.ContentId);
mail.IsBodyHtml = true;
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("******", "******");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
You have missed the attachment.
Your linked resource also needs to be attached to the email. You need to add the following code:
mail.Attachments.Add(att);
HELP! So i have this issue wherein theres a "noname" attachment when sending emails with pictures as seen below
Now, i want this to remove since it is not part of my emailer.
heres is my code below
public static bool SendEmailNotification(List<string> toList, List<string> ccList, string subject, string body)
{
bool isSent = true;
try
{
var mail = new MailMessage();
var smtpClient = new SmtpClient(Constants.SMTP.SMTPClient);
var alternateView = AlternateView.CreateAlternateViewFromString(body, null, Constants.SMTP.Format);
mail.From = new MailAddress(Constants.SMTP.EmailAddress);
if (toList != null && toList.Any())
{
foreach (var email in toList)
{
mail.To.Add(email);
}
if (ccList != null && ccList.Any())
{
foreach (var email in ccList)
{
mail.CC.Add(email);
}
}
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.AlternateViews.Add(alternateView);
smtpClient.Credentials = new NetworkCredential(Constants.SMTP.EmailAddress,
Constants.SMTP.EmailPassword, Constants.SMTP.Email);
smtpClient.Send(mail);
}
else
{
isSent = false;
}
}
catch
{
isSent = false;
}
return isSent;
}
The attachment is actually your image payload in binary. It's set to "noname". Reason being is certain parameters aren't set properly. In this case, to do it properly refer to https://brutaldev.com/post/sending-html-e-mail-with-embedded-images-(the-correct-way)
if( attachementFile!=null)
{
Attachment attachment = new Attachment(attachementFile, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachementFile);
disposition.ModificationDate = File.GetLastWriteTime(attachementFile);
disposition.ReadDate = File.GetLastAccessTime(attachementFile);
disposition.FileName = Path.GetFileName(attachementFile);
disposition.Size = new FileInfo(attachementFile).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
return attachment;
}
Here's the code from the link in #kendolew's answer with an example on how to properly include an attachment:
public static void SendMessageWithEmbeddedImages()
{
string htmlMessage = #"<html>
<body>
<img src='cid:EmbeddedContent_1' />
</body>
</html>";
SmtpClient client = new SmtpClient("mail.server.com");
MailMessage msg = new MailMessage("noreply#deventerprise.net",
"someone#deventerprise.net");
// Create the HTML view
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
htmlMessage,
Encoding.UTF8,
MediaTypeNames.Text.Html);
// Create a plain text message for client that don't support HTML
AlternateView plainView = AlternateView.CreateAlternateViewFromString(
Regex.Replace(htmlMessage,
"<[^>]+?>",
string.Empty),
Encoding.UTF8,
MediaTypeNames.Text.Plain);
string mediaType = MediaTypeNames.Image.Jpeg;
LinkedResource img = new LinkedResource(#"C:\Images\MyImage.jpg", mediaType);
// Make sure you set all these values!!!
img.ContentId = "EmbeddedContent_1";
img.ContentType.MediaType = mediaType;
img.TransferEncoding = TransferEncoding.Base64;
img.ContentType.Name = img.ContentId;
img.ContentLink = new Uri("cid:" + img.ContentId);
htmlView.LinkedResources.Add(img);
//////////////////////////////////////////////////////////////
msg.AlternateViews.Add(plainView);
msg.AlternateViews.Add(htmlView);
msg.IsBodyHtml = true;
msg.Subject = "Some subject";
client.Send(msg);
}
I am working with asp .net. I want to send an authentication code to user's email when he sign up. I'm using this code to send email. I'm adding a html file to send. How can I add the authentication code to this HTML file?
This is the code which I used to send the html file via Email. So how can I add a string(authenticationCode) to HTML file to send it to the user for authentication.
var fromAddress = new MailAddress("hamza230#gmail.com", "From Hamza");
var toAddress = new MailAddress("usama90#gmail.com", "To Usama");
const string fromPassword = "****";
const string subject = "email";
const string body = "hello world";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
MailMessage message = new MailMessage(fromAddress, toAddress);
message.Subject = subject;
message.Body = body;
message.BodyEncoding = Encoding.UTF8;
String plainBody = "Title";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, Encoding.UTF8, "text/plain");
message.AlternateViews.Add(plainView);
MailDefinition msg = new MailDefinition();
msg.BodyFileName = "~/newsletter.html";
msg.IsBodyHtml = true;
msg.From = "usamaazam10#gmail.com";
msg.Subject = "Subject";
ListDictionary replacements = new ListDictionary();
MailMessage msgHtml = msg.CreateMailMessage("usamaazam10#gmail.com", replacements, new LiteralControl());
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, Encoding.UTF8, "text/html");
LinkedResource logo = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/logo.jpg"), MediaTypeNames.Image.Jpeg);
logo.ContentId = "logo";
htmlView.LinkedResources.Add(logo);
LinkedResource cover = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/cover.jpg"), MediaTypeNames.Image.Jpeg);
cover.ContentId = "cover";
htmlView.LinkedResources.Add(cover);
message.AlternateViews.Add(htmlView);
smtp.Send(message);
You can do this for small html pages
string smalHhtml = "<body>"
+ "your some designing"
+ "your Code : " + code
+ "</body>";
Note: This is for small body html and sending verification code via email is usually small html.
You can add the authentication code to the message body, for example:
...
message.Body = body + authenicationCode;
...
Or, if you don't create body as a const then you can create it at the top of your code, for example;
...
const string subject = "email";
string body = "Your authentication code is: " + authenicationCode;
...
I am using the attached code to send email and images. It is working with gmail.
Now, I want to send to email using html templates. How do I use the attached code to do it?
private void SendEmail1()
{
string strMailContent = "Welcome new user";
string fromAddress = "xxx";
string toAddress = "xxx";
string contentId = "image1";
string path = Server.MapPath(#"Images/ml2.png"); // my logo is placed in images folder
MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
mailMessage.Subject = "Welcome new User";
LinkedResource logo = new LinkedResource(path,"image/png");
logo.ContentId = "companylogo";
// done HTML formatting in the next line to display my logo
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, "text/html");
av1.LinkedResources.Add(logo);
mailMessage.AlternateViews.Add(av1);
mailMessage.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.UseDefaultCredentials = true;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}
Looks like your html isn't formatted correctly
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, "text/html");
Should be
AlternateView av1 = AlternateView.CreateAlternateViewFromString($"<html><body><img src=cid:companylogo/><br>{strMailContent}</body></html>", "text/html");
Looks like your html isn't formatted correctly and you're passing in a null encoding.
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, "text/html");
Should be
AlternateView av1 = AlternateView.CreateAlternateViewFromString($"<html><body><img src=cid:companylogo/><br>{strMailContent}</body></html>", "text/html");
I have an ASP.Net MVC application. I need to send html content from HTML-Editor. but I have problem with it.
This is my Html-Editor:
This is my code:
public void MailMessageHtml(string body, string subject, string from, IEnumerable<string> to)
{
var message = new MailMessage();
message.To.Add(new MailAddress("myemail#example.com"));
message.From = new MailAddress(_Settings.MailServer.UserName);
message.Subject = subject;
message.IsBodyHtml = true;
var htmlBody = AlternateView.CreateAlternateViewFromString(
body, Encoding.UTF8, "text/html");
message.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(string.Empty, new ContentType("text/plain")));
message.AlternateViews.Add(htmlBody);
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = _Settings.MailServer.UserName,
Password = _Settings.MailServer.Password
};
smtp.Credentials = credential;
smtp.Host = _Settings.MailServer.IPAddress;
smtp.Port = _Settings.MailServer.Port;
smtp.EnableSsl = _Settings.MailServer.EnableSSL;
smtp.Send(message);
}
}
but the html content in Email's body has shown like this:
What should I do?
You need to Decode the content before passing the content to the body.
body = HttpUtility.HtmlDecode(body);
Just this.