I'm trying to insert an image in an email following this http://www.codeproject.com/Tips/326346/How-to-embed-a-image-in-email-body
but for some images are not showing in the mail.
Here is the code.
var message = new MailMessage();
message.From = new MailAddress("noreply#happy.com");
message.To.Add("testmail#gmail.com");
var body = new StringBuilder();
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
var path = #"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg";
AlternateView altView = AlternateView.CreateAlternateViewFromString("testing mail: <img src=cid:myImage>", null, MediaTypeNames.Text.Html);
LinkedResource imageToSend = new LinkedResource(path);
imageToSend.ContentId = "myImage";
altView.LinkedResources.Add(imageToSend);
message.AlternateViews.Add(altView);
var smtp = new SmtpClient();
smtp.Send(message);
Related
I can send attachments with URLs, But, looking for support to send a file with an attachment. that too should download from url and attach with mail.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#email.com");
//to mail address
mail.To.Add(txtEmail.Text);
//Add the Attachment
mail.Attachments.Add(data);
//set the content
mail.Subject = txtSubject.Text;
mail.Body = "Kindly find the below attachments with the link, https://www.python.org/static/img/python-logo#2x.png";
//send the message
SmtpClient smtp = new SmtpClient("*****.********.net");
NetworkCredential Credentials = new NetworkCredential("mymail#email.com", "********");
smtp.Credentials = Credentials;
smtp.Send(mail);
Here I'm sending mail with URL as a file,
But I want to attach a file instead of sending a link
The sample URL was added as an image link.. But I wanted to add a pdf link..
In this case, I want to download a file and attach it with mail,
I use it mostly in my all projects it's working fine. its with base 64
First, make sure your Gmail account is turned on for sending emails.
public static async Task SendEmail(string toUser, string subject, string body
, string username, string password, string port, string smtpServer, string ccUsers = "", string base64Url = "")
{
var toAddress = new System.Net.Mail.MailAddress(toUser, toUser);
System.Net.Mail.MailMessage emessage = new System.Net.Mail.MailMessage();
emessage.To.Add(toAddress);
if (!string.IsNullOrEmpty(ccUsers))
{
string[] ccIds = ccUsers.Split(',');
foreach (string item in ccIds)
{
emessage.CC.Add(new System.Net.Mail.MailAddress(item));
}
}
emessage.Subject = subject;
emessage.From = new System.Net.Mail.MailAddress(username);
emessage.Body = body;
emessage.IsBodyHtml = true;
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
if (!string.IsNullOrEmpty(base64Url))
{
base64Url = base64Url.Replace("data:image/jpeg;base64,", "");
var imageBytes = Convert.FromBase64String(base64Url);
var stream = new MemoryStream(imageBytes);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg);
System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(stream, ct);
at.ContentDisposition.FileName = "Invoice.jpeg";
emessage.Attachments.Add(at);
}
var netCredential = new System.Net.NetworkCredential(username, password);
sc.Host = smtpServer;
sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
sc.UseDefaultCredentials = false;
sc.Credentials = netCredential;
sc.EnableSsl = true;
sc.Port = Convert.ToInt32(port);
await sc.SendMailAsync(emessage);
}
It works fine and mail directly reaches inbox instead of spam.. also can able to attach files from serverpath. Thank you everyone who wish to answer my questions..
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#gmail.com");
mail.To.Add("tomail#gmail.com");
//set the content
string filename = "Report1";
string fileurl = Server.MapPath("..");
fileurl = fileurl + #"\mailserver\pdf\generated\" + filename + ".pdf";
//mail.Attachments.Add(new Attachment(fileurl));
if (!string.IsNullOrEmpty(fileurl))
{
Attachment attachment = new Attachment(fileurl, MediaTypeNames.Application.Pdf);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(fileurl);
disposition.ModificationDate = File.GetLastWriteTime(fileurl);
disposition.ReadDate = File.GetLastAccessTime(fileurl);
disposition.FileName = Path.GetFileName(fileurl);
disposition.Size = new FileInfo(fileurl).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
mail.Attachments.Add(attachment);
}
mail.Subject = "Subject Text";
mail.Body = "Body Text";
//send the message
SmtpClient smtp = new SmtpClient("smtpout.****.******server.net");
NetworkCredential Credentials = new NetworkCredential("mymail#gmail.com", "Password#123");
smtp.Credentials = Credentials;
//smtp.EnableSsl = true;
smtp.Send(mail);
Response.Write("<center><span style='color:green'><b>Mail has been send successfully!</b></span></center>");
}
catch (Exception ex)
{
//Response.Write("<center><span style='color:red'><b>"+ ex + "</b></span></center>");
Response.Write("<center><span style='color:red'><b>Failed to send a mail...Please check your mail id or Attachment missing</b></span></center>");
}
}
I want to send an e-mail with a logo at the top of the body. This is my method:
public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo style=\"height: 50px;\"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = port;
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
The method is sending the e-mail, but the image is being sent as an attachment. I've tried to do this:
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"), MediaTypeNames.Image.Jpeg);
But when I add "MediaTypeNames.Image.Jpeg" in this line, the e-mail is sent without the image at all.
Someone can help me on this? Thanks in advance!
You could convert your image to base64 and add that in src or you could just give the page where is the image is located.
You could try the library MailKit. Sending embedded images works well with this library.
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Png);
stream.Position = 0;
var resource = builder.LinkedResources.Add(contentId, stream);
resource.ContentId = contentId;
// in the email message, there is img with src="cid:contentId"
Another example of embedding images is here.
You can use it :
public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo style=\"height: 50px;\"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = 0; //add port here
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
//add file here
Attachment attachment = new Attachment("c://image");
attachment.ContentDisposition.Inline = true;
message.Attachments.Add(attachment);
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
I am using following code to send email but it is failed if I used html attachment.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer2 = new System.IO.StreamWriter(ms);
writer2.Write("<html><head></head><body>Invoice 1</body></html>");
writer2.Flush();
writer2.Dispose();
MailMessage mm = new MailMessage();
mm.To.Add("test#gmail.com");
mm.CC.Add("test2#gmail.com");
mm.From = new MailAddress("test3#gmail.com");
mm.Subject = "नोटिस";
mm.Body = sb.ToString();
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Html);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = "myFile.html";
mm.Attachments.Add(attach);
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "rcms.pdf"));
ms.Close();
mm.IsBodyHtml = true;
only one line needed.
var a = System.Net.Mail.Attachment.CreateAttachmentFromString("'"+sb.ToString()+"'</body>", "notices.html");
I have written below code to embed image in the mail which is being sent from my c# code. But when i check the mail, i get image like an attachment and not as an inline image. (Gmail)
AlternateView htmlBodyView = null;
string htmlBody = "<html><body><h1></h1><br><img src=\"cid:SampleImage\"></body></html>";
AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
ImageConverter ic = new ImageConverter();
Byte[] ba = (Byte[])ic.ConvertTo(bitmap_obj, typeof(Byte[]));
using (MemoryStream logo = new MemoryStream(ba))
{
LinkedResource sampleImage = new LinkedResource(logo, "image/jpeg");
sampleImage.ContentId = "sampleImage";
htmlBodyView.LinkedResources.Add(sampleImage);
p.SendEmail(htmlBodyView);
}
For reference, a full working simplified example:
public void SendMail()
{
LinkedResource logo = new LinkedResource(
"images\\image005.png", //Path of file
"image/png"); //Mime type: Important!
logo.ContentId = "logo"; //ID for reference
//Actual HTML content of the body in an 'AlternateView' object.
AlternateView vw = AlternateView.CreateAlternateViewFromString(
"Hello, this is <b>HTML</b> mail with embedded image: <img src=\"cid:logo\" />",
null,
MediaTypeNames.Text.Html); //Mime type: again important!
vw.LinkedResources.Add(logo);
var msg = new MailMessage() { IsBodyHtml = true };
msg.AlternateViews.Add(vw);
msg.From = new MailAddress("sender#domain.com");
msg.To.Add(new MailAddress("reciever#domain.com"));
msg.Subject = "HTML Mail!";
using (var client = new SmtpClient("localhost", 25))
client.Send(msg);
}
How can i add an image to an email message sent from a web server in C#
this is the code i am using:
string emailType = "NewMember";
string sMessage = GetData.emailText(emailType);
string sEmail = GetData.userEmails(userName);
string sSubject = GetData.emailSubject(emailType);
SmtpClient smtpClient = new SmtpClient();
string htmlBody = "<html><body>Dear " + userName + sMessage + "<br/><br/><img src=\"cid:filename\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource("~/Resources/images/logo.jpg", MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
avHtml.LinkedResources.Add(inline);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(avHtml);
Attachment att = new Attachment("~/Resources/images/logo.jpg");
att.ContentDisposition.Inline = true;
MailAddress sFrom = new MailAddress("info#website.com");
MailAddress sTo = new MailAddress(sEmail);
mail.From = sFrom;
mail.To.Add(sTo);
mail.Subject = sSubject;
mail.Body = String.Format(
htmlBody +
#"<img src=""cid:{0}"" />", inline.ContentId);
mail.IsBodyHtml = true;
mail.Attachments.Add(att);
smtpClient.Send(mail);
`
this is the error message i am getting:
Could not find a part of the path 'C:\Windows\SysWOW64\inetsrv\~\Resources\images\logo.jpg
Try -
Attachment att = new Attachment(Server.MapPath("~/Resources/images/logo.jpg"));
LinkedResource inline = new LinkedResource(Server.MapPath("~/Resources/images/logo.jpg"), MediaTypeNames.Image.Jpeg);
Instead of -
Attachment att = new Attachment("~/Resources/images/logo.jpg");
LinkedResource inline = new LinkedResource("~/Resources/images/logo.jpg", MediaTypeNames.Image.Jpeg);
Because you need the path of the resource that is inside website folder. So you have to map path with Server.MapPath. More details here -
Server.MapPath Method