Send e-mail with image on body - c#

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;
}
}

Related

Adding attachments using url in mail with C sharp

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>");
}
}

Links not getting created while sending email through asp.net mvc

Hi i am sending download brochure link in the email but i am receiving only text instead of link in the mail
below is the code from which i am sending the mail
StringBuilder sb = new StringBuilder();
sb.Append("<html><body><a href='"+Server.MapPath("~/Documents/Brochure.pdf") +"'>Download Brochure </a>");
sb.Append("<br></body></html>");
string messageBody = sb.ToString();
string AdminEmail = ConfigurationManager.AppSettings["AdminEmailForEmail"];
string AdminPassword = ConfigurationManager.AppSettings["AdminPasswordForPassword"];
string Reciepient = Email;
string subject = "Brochure Download";
string FromMail = "info#testmail.in";
string emailTo = Reciepient;
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("testmail.in");
mail.From = new MailAddress(FromMail);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = messageBody;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential(AdminEmail, AdminPassword);
SmtpServer.EnableSsl = false;
try
{
SmtpServer.Send(mail);
return true;
}
catch (Exception ex)
{
return false;
}

Insert image in email

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);

Time out error while sending mail to gmail account using smtp port 465 in asp.net

public void SendEmailWithAttachment(string pFrom, string pTo, string pSubject, string pBody, string pServer, string strAttachmentPDFFileNames)
{
try
{
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
string UserName = ConfigurationManager.AppSettings["SMTPUserName"];
string Password = ConfigurationManager.AppSettings["SMTPPassword"];
if (pTo.Contains(","))
{
string[] ToAdd = pTo.Split(new Char[] { ',' });
for (int i = 0; i < ToAdd.Length; i++)
{
Message.To.Add(ToAdd[i]);
}
}
else
{
Message.To.Add(pTo);
}
//System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(pTo);
//Message.To.Add(toAddress);
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress(pFrom);
Message.From = fromAddress;
Message.Subject = pSubject;
Message.Body = pBody;
Message.IsBodyHtml = true;
// Stream streamPDFImages = new MemoryStream(bytPDFImageFile);
//System.Net.Mail.SmtpClient
var smtpClient = new System.Net.Mail.SmtpClient();
{
Message.Attachments.Add(new System.Net.Mail.Attachment(strAttachmentPDFFileNames));
smtpClient.EnableSsl = true;
smtpClient.Host = pServer;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
smtpClient.Port = 465;
smtpClient.Send(Message);
}
}
catch (Exception Exc)
{
Exception ex = new Exception("Unable to send email . Please Contact administrator", Exc);
throw ex;
}
}
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("yourMail", "yourPassword");
smtp.EnableSsl = true;
MailMessage msg = new MailMessage(sendFrom, "yourMail");
msg.ReplyToList.Add(sendFrom);
msg.Subject = subject;
msg.Body = bodyTxt;
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(#"C:\Projects\EverydayProject\test.txt");
msg.Attachments.Add(attachment);
smtp.Send(msg);
Here is working code to send an email to gmail smtp. From what I see you don't set UseDefaultCredentials = false and you are using wrong port. Also you MUST NOT override exceptions like this., throw the initial exception. Also for this to work you need to turn off security setting in your Gmail account. You can google it.

how to release file lock while mail attachment in loop in c#?

i am sending single mail to more than 1 person. so i am sending mail in for loop with attachement.but while in second loop i am getting file lock error.below is my code.
public string SendMail(string toList, string from, string ccList,
string subject, string body)
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
try
{
MailAddress fromAddress = new MailAddress(from);
message.From = fromAddress;
message.To.Add(toList);
if (ccList != null && ccList != string.Empty)
message.CC.Add(ccList);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
// We use gmail as our smtp client
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential(TextBox1.Text, TextBox2.Text);
if (FileUpload2.HasFile)
{
// File Upload path
String FileName = FileUpload2.PostedFile.FileName;
FileUpload2.PostedFile.SaveAs(Server.MapPath(FileName));
//Getting Attachment file
Attachment mailAttachment = new Attachment(Server.MapPath(FileName));
//Attaching uploaded file
message.Attachments.Add(mailAttachment);
}
smtpClient.Send(message);
LblMessage.ForeColor = System.Drawing.Color.Green;
LblMessage.Text = "Mail Sent Successfully.";
}
catch (Exception ex)
{
LblMessage.Text = ex.Message;
LblMessage.ForeColor = System.Drawing.Color.Red;
}
return msg;
}
in loop calling this function
for (int i = 0; i < LbEmails.Items.Count; i++)
{
SendMail(LbEmails.Items[i].ToString(), TextBox1.Text, "", TbSubject.Text, TbBody.Text);
}
It looks like you're saving the uploaded file once for each email you send even though it seems to be the same for all the emails. Pull this line out of the SendMail() method and call it before your loop:
FileUpload2.PostedFile.SaveAs(Server.MapPath(FileName));

Categories