Sending Image in email with text retrieved from DB - c#

Currently we stored email text in db table and when we send an email, we query the db get the email text, do an HTML Encode and send email. But now we need to send Images in the email. What I did was stored the image in project file and stored the image location as tag in email text in db table. But its not working, any ideas on how should i do this. I need to insert image in middle of text. This is how we store html email in db table. As html is being parsed I copied it in comments section.

Pass your body to an html form and allowhtml(true) while sending email like this
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();
SmtpServer.Host = Host;
mail.IsBodyHtml = true;
mail.From = new MailAddress(FromEmail);
mail.To.Add(ToEmail);
mail.Body = MailBody;
such that MailBody is String.Format("{0} with < img href='{1}' />",email,imagesrc);
{0} will be replaced by email
{1} will be replaced by imagesrc

you have to upload your picture to a webserver and set the src of the image to the absolute path!
<img src="http://www.myuploaded.com/image.jpg" />
if you cannot do that look at this post:
how to embed image in email

Related

ASP.NET MVC Forget Password email link not formatting as Html

I am trying to set up a forgot password feature, but I can't get the body of the email formatted with links. I think the email is not set up for Html.
void sendMail(IdentityMessage message)
{
#region formatter
string text = string.Format("", message.Subject, message.Body);
string html = "";
html += HttpUtility.HtmlEncode(#"" + message.Body);
#endregion
MailMessage msg = new MailMessage();
msg.From = new MailAddress(ConfigurationManager.AppSettings["Email"].ToString());
msg.To.Add(new MailAddress(message.Destination));
msg.IsBodyHtml = true;
msg.Subject = message.Subject;
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
SmtpClient smtpClient = new SmtpClient("smtp-mail.outlook.com", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["Email"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
smtpClient.Credentials = credentials;
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
}
How I use it:
await UserManager.SendEmailAsync(user.Id, "Holiday Tracker Reset Password", "Please reset your password by using the following link. here ");
I would like the code to work so the email has a clickable link instead of just the long string of the url.
You haven't provided any sample of your message body data, or sample source markup of the generated emails, so it's hard to be 100% of the root cause, but here are a few little issues here which might be contributing:
1) You never actually set the main body text of your email. You set alternative views, but not the base body. So even though you set the IsBodyHtml option, there's nothing for it to act upon.
2) You've added two identical alternative views. It probably doesn't matter, but it's clearly redundant. If you've set the body to HTML, and then actually included body text, you shouldn't need these alternative views anyway.
3) The above are niggles, but I think this is the clincher: I strongly suspect you have misunderstood what HttpUtility.HtmlEncode() does.
Consider the following example:
string myString = "<b>Hello World</b>";
// Encode the string.
string myEncodedString = HttpUtility.HtmlEncode(myString);
Console.WriteLine($"HTML Encoded string is: {myEncodedString}");
StringWriter myWriter = new StringWriter();
// Decode the encoded string.
HttpUtility.HtmlDecode(myEncodedString, myWriter);
string myDecodedString = myWriter.ToString();
Console.Write($"Decoded string of the above encoded string is: {myDecodedString}");
This will output:
HTML Encoded string is: <b>Hello World</b>
Decoded string of the above encoded string is: <b>Hello World</b>
Live Demo: https://dotnetfiddle.net/9j46WN
As you can see, encoding a string containing HTML will convert the HTML control characters into their encoded representation. This is generally used to ensure the characters are not treated as HTML when viewed (i.e. they are seen as pieces of text to be displayed on screen, not interpreted as part of the HTML document's markup). This is the exact opposite of what you want.
e.g. when I put those two strings into this HTML page as raw markup (rather than in a "code" block), it comes out as:
HTML Encoded string is: <b>Hello World</b>
Decoded string of the above encoded string is: Hello World
Notice how the encoded one displays the HTML rather than using it?
So I think you can drop the Html-encoding. Assuming you are already supplying HTML markup to your method in message.Body, then you can use it as-is. And if you set your message body in the normal way, you should be able to dispense with the alternative views as well. Here's what I think your code should be changed to:
void sendMail(IdentityMessage message)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(ConfigurationManager.AppSettings["Email"].ToString());
msg.To.Add(new MailAddress(message.Destination));
msg.IsBodyHtml = true;
msg.Body = message.Body;
msg.Subject = message.Subject;
SmtpClient smtpClient = new SmtpClient("smtp-mail.outlook.com", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["Email"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
smtpClient.Credentials = credentials;
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
}

Attachment without filename

When using the System.Net.Mail namespace to send a e-mail with attachment to any Yahoo account the attachment is downloaded with 'untitled' name instead the file name.
In the Yahoo Mail interface the attachment looks with the correct name but when you download it the download name goes to 'untitled' for all attachments. The same e-mail message works fine with Gmail, Outlook.com, Windows Live Mail and other clients.
Looking the raw message it constains a content-type with name but without filename attribute. The Yahoo works fine if the filename attribute is set but C# library don't use this.
That's the header generated by C# for attachments:
Content-Type: application/octet-stream; name=test.pdf
That's the header that works with Yahoo:
Content-Type: application/octet-stream; name=file2; filename=test.pdf
Anyone get this problem so far? Is there a work arround for C# default mail sending?
using (var message = new MailMessage("from#domain", "to#yahoo.com.br", "Test with attachment", "Test with attachment"))
{
var attachment = new Attachment(#"c:\temp\test.pdf"); // Same result using stream instead path to file.
attachment.Name = "test.pdf"; // Same result without this line.
message.Attachments.Add(attachment);
using (var smtp = new SmtpClient("smtp.domain", 587))
{
smtp.Credentials = new NetworkCredential("from#domain", "password");
smtp.Send(message);
}
}
I found a solution:
attachment.ContentDisposition.FileName = "test.pdf";
This add the missing filename attribute in the raw e-mail message and solve the Yahoo limitation.
Have you tried explicitly specifying the content type?
var attachment = new Attachment(... , MediaTypeNames.Application.Octet);

How to send HTML email with multiple Images

i want to send html mail with multiple images. i am using webbrowsercontrol to embedded multiple images but when i send mail HTML email along with Image in HTML then I receive only html mail without Image.!
Try with LinkedResource Class to embed the image
using System.Net.Mail;
string messageHtml= #"<html><body> Your message text
<img src=""cid:12345"" />
<img src=""cid:123456"" /></body></html>";
AlternateView view= AlternateView.CreateAlternateViewFromString(messageHtml, null, MediaTypeNames.Text.Html);
LinkedResource pic= new LinkedResource("pics.jpg", MediaTypeNames.Image.Jpeg);
pic.ContentId = "12345";
LinkedResource pic2= new LinkedResource("pic2.jpg", MediaTypeNames.Image.Jpeg);
pic2.ContentId = "123456";
view.LinkedResources.Add(pic);
view.LinkedResources.Add(pic2);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(view);
mail.send();

SMTP Permission Error

I'm using system.net.mail and have a textbox that users can enter their email address and a file gets attached and sent to them. When I test this in my custom box with Server 2008 I get the following error:
Request for the permission of type 'System.Net.Mail.SmtpPermission....at System.Security.CodeAccessSecurityEngine.Check
Do I have to configure something specifically on the server to allow? Or is it a code error?
string strto = txtTo.Text;
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("serveremail");
mail.To.Add(strto);
//set the content
mail.Subject = "subject";
//Get some binary data
byte[] byteArray = Encoding.ASCII.GetBytes(result);
//save the data to a memory stream
using (MemoryStream ms = new MemoryStream(byteArray))
//create the attachment from a stream. Be sure to name the data with a file and
//media type that is respective of the data
mail.Attachments.Add(new Attachment(ms, "test.txt", "text/plain"));
//send the message
SmtpClient smtp = new SmtpClient("server");
smtp.Send(mail);
This looks like it could be a permission issue when trying to access the attachment from the steam. What happens if you explicitly state credentials?

setting mail header in c#

hi i need to set header content type in c#.
when i send mail from c#, i'm getting the mail with html tags. how can set content type in mail sending code?
In case that you asking how can I send email in c#:
MailMessage mail = new MailMessage();
mail.To = "me#mycompany.com";
mail.From = "you#yourcompany.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
mail.IsBodyHtml = false;
SmtpMail.SmtpServer = "localhost"; //your real server goes here
SmtpMail.Send( mail );
Source: here.
MailMessage mail = new MailMessage();
// need to set this property
mail.IsBodyHtml = false;
For more alterations, you can do with templates in your email, see
Can I set up HTML/Email Templates in
C# on ASP.NET?
Hope this helps

Categories