Image path not found - c#

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

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

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

Attach text file to mail using C# for Windows-mobile

I have this sample C# code for sending mail Through Windows-Mobile 6.5:
EmailMessage message = new EmailMessage();
Recipient myrecipient = new Recipient("Gmail", "MyMail#gmail.com");
message.To.Add(myrecipient);
message.Subject = "test from Windows-Mobile";
message.BodyText = "this is the test from Windows-Mobile";
message.Send("Gmail");
MessagingApplication.Synchronize("Gmail");
SetForegroundWindow(this.Handle);
How to send for more than one mail address ?
How to attach text file to mail ?
Try this:
To attach file with more details like name/size.
Attachment attachment = new Attachment(outputFile, MediaTypeNames.Text.Html);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(outputFile);
disposition.ModificationDate = File.GetLastWriteTime(outputFile);
disposition.ReadDate = File.GetLastAccessTime(outputFile);
disposition.FileName = Path.GetFileName(outputFile);
disposition.Size = new FileInfo(outputFile).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
smtp.Send(message);
link for ref:
https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.attachments%28v=vs.110%29.aspx
EmailMessage message = new EmailMessage();
Recipient myrecipient = new Recipient("Gmail", "MyMail#gmail.com");
message.To.Add(myrecipient);
//Adding more To address
message.To.Add(myrecipient2);
message.To.Add(myrecipient3);
//Adding more CC address
message.Cc.Add(myrecipient4);
message.Cc.Add(myrecipient5);
//Adding more Bcc address
message.Bcc.Add(myrecipient6);
message.Bcc.Add(myrecipient7);
message.Subject = "test from Windows-Mobile";
message.BodyText = "this is the test from Windows-Mobile";
//Adding attachments
message.Attachments.Add("TextFilePath");
message.Send("Gmail");
MessagingApplication.Synchronize("Gmail");
SetForegroundWindow(this.Handle);

Attaching an image to email [duplicate]

This question already has answers here:
How to embed multiple images in email body using .NET
(7 answers)
Closed 9 years ago.
i trying to send test email from my local dev machine, with an image. the image is not being sent as an attachment.
May be its a stupid question but is there any way i can send email from my website running on my local machine for test purposes before i host it on www.
public static void SendMail(string emailBody, string to, string from, string subject)
{
MailMessage mailMessage = new MailMessage("to#to.com", "from#test.com");
mailMessage.Subject = subject;
mailMessage.Body = emailBody;
mailMessage.IsBodyHtml = true;
//mailMessage.Body += "<br /><br /> <asp:Image ID='Image1' runat='server' ImageUrl='~/images/banner.jpg' />";
string path = System.Web.HttpContext.Current.Server.MapPath(#"~/images/banner.jpg");
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><br/><img src=cid:companylogo/><br></body></html>" + emailBody, null, MediaTypeNames.Text.Html);LinkedResource logo = new LinkedResource(path);
av1.LinkedResources.Add(logo);
mailMessage.AlternateViews.Add(av1);
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand sc = new SqlCommand("SELECT EmailAdd FROM Volunteers where Country like 'United K%' and Race like 'Pak%' ", con);
con.Open();
SqlDataReader reader = sc.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
mailMessage.To.Add(reader[0].ToString());
}
}
reader.Close();
}
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
}
It looks as though you may not be setting the correct CID of the image. This is the method I'm using in one of my applications:
// Construct the MailMessage object to be relayed to the SMTP server
message = new MailMessage("to#to.com", "from#test.com");
string path = System.Web.HttpContext.Current.Server.MapPath(#"~/images/banner.jpg");
byte[] image = LoadImageAsByteArray(path);
// create a stream object from the file contents
var stream = new MemoryStream(image);
// create a mailAttachment object
var mailAttachment = new System.Net.Mail.Attachment(stream, "bannerAttachment.jpg")
{
// set the content id of the attachment so our email src links are valid
ContentId = Guid.NewGuid().ToString("N")
};
// set the attachment inline so it does not appear in the mail client as an attachment
mailAttachment.ContentDisposition.Inline = true;
// and then add the newly created mailAttachment object to the Attachments collection
message.Attachments.Add(mailAttachment);
And...one thing I found "strange" is your use of AlternateView - it seems a bit redundant. I'd advise creating the body like so:
// Construct the body
var body = string.Format("<html><body><br/><img src=cid:{0} /><br />{1}</body></html>", mailAttachment.ContentId, emailBody);
// Subject
message.Subject = "Whatever"
// Ensure this is set to true so images are embedded correctly
message.IsBodyHtml = true;
// finally, add the body
message.Body = body;
// Create an smtp client object to initiate a connection with the server
var client = new SmtpClient(smtpServerAddress, smtpServerPort.Value);
// tell the client that we will be sending via the network (as opposed to using a pickup directory)
client.DeliveryMethod = SmtpDeliveryMethod.Network;
// and finally send the message
client.Send(message);
);
NOTE: You'll have to take care of your own authentication etc. as I have not included that. Also, this is an excerpt of my own production code, so please, let me know how you go. I'll be more than happy to modify my answer accordingly.
here is your solution.
string ss = "<div style='background:#e0e1e3;width:800px; margin:20px auto;border:1px solid #d8d9db;'>";
ss = ss + "<div style='background:#ffffff; padding:10px;'>";
ss = ss + "<img src='http://example.com/images/myimage.jpg' /></div>";
MailMessage MailMsg = new MailMessage();
MailMsg.To.Add("test#test.com");
MailMsg.From = new MailAddress("Test.co.in");
MailMsg.Subject = "Your subject";
MailMsg.BodyEncoding = System.Text.Encoding.UTF8;
MailMsg.IsBodyHtml = true;
MailMsg.Priority = MailPriority.High;
MailMsg.Body = ss;
SmtpClient tempsmtp = new SmtpClient();
tempsmtp.Host = "smtp.gmail.com";
tempsmtp.Port = 587;
tempsmtp.EnableSsl = true;
tempsmtp.Credentials = new System.Net.NetworkCredential("test#test.com", "welcome");
tempsmtp.DeliveryMethod = SmtpDeliveryMethod.Network;
tempsmtp.Send(MailMsg);

is not a valid virtual path in SiteMap

hello i want to send an mail of image from Asp.net.
i got an error like this :: 'http://domain-name.com/slideshow/original/Jellyfish.png' is not a valid virtual path.
my code is :
try
{
string _SenderEmailID = ReciverEmailID.Text.ToString();
string _ReciverEmailID = ReciverEmailID.Text.ToString();
string _Sender = FullName.Text.ToString();
string post = "JellyBeans.png";
string ImagePath = "http://www.domain-name.com/slideshow/original/";
string iImage = ImagePath + post;
img1.ImageUrl = ImagePath;
MailMessage mail = new MailMessage();
mail.To.Add(_ReciverEmailID);
mail.From = new MailAddress(_SenderEmailID);
mail.Subject = _Sender + " sent you a mail from 'www.domain-name.com";
string Body = "<img alt=\"\" hspace=0 src=\"cid:imageId\" align=baseline border=0 >";
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");
LinkedResource imagelink = new LinkedResource(Server.MapPath(ImagePath)+ #post, "image/png");
imagelink.ContentId = "imageId";
imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(imagelink);
mail.AlternateViews.Add(htmlView);
SmtpClient smtp = new SmtpClient();
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.Send(mail);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Remove
Server.MapPath
from the line
LinkedResource imagelink = new LinkedResource(Server.MapPath(ImagePath)+ #post, "image/png");
Server.MapPath is used when the path is in your application, a virtual path. Your image url is a direct url or physical path so MapPath is not needed.
Returns the physical file path that corresponds to the specified
virtual path on the Web server.
You would use MapPath if your image was in your VisualStudio solution.

Categories