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.
Related
I am sending an email with a link that a customer will click and the zip file will get downloaded. but the issue now is that, when I click the link, nothing happens or the zip file doesn't get downloaded. I have searched around but I didn't get what am looking for.
The zip file does exist in the file server \127.0.0.1\Folder1...
How can I download a zip file from a link?
This is my code
public void SendingEmail(string emailTo, string subject, string body, string ZipeFileName = null)
{
string emailHost = "myhost";
string fromEmail = "myemail#domain";
emailTo = "test#gmail.com";
try
{
WebClient myClient = new WebClient();
ZipeFileName = "ApplicationDocuments.zip";
var filePath = #"\\127.0.0.1\Folder1\" + ZipeFileName + "";
var newFileName = Path.GetFileName(filePath);
var DownLoadlink = "<a download href='" + filePath + "'>Click me to DownLoad<\a>";
myClient.DownloadFileAsync(new Uri(filePath), newFileName);
SmtpClient smtp = new SmtpClient(emailHost, 25)
{
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
};
using (var message = new MailMessage(fromEmail, emailTo)
{
Subject = subject,
Body = "Thank for downloading your file. To download, please " + DownLoadlink + "",
})
{
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
smtp.Send(message);
}
#endregion
//End
}
catch (Exception ex)
{
throw ex;
}
}
The folder on localhost (127.0.0.1) is not available from outside of your computer.
Place your file on your portal or ftp site and add the proper address with http(s) or (s)ftp protocol.
Alternatively you can use a shared folder on your computer but this must be accessible from the internet (or where your customers are) what is not recommended.
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 would like to read a webpage screenshot and send it to email in C# without save it as File. Right now my email message body only shows this message: "This is the initial start page for the WebDriver server", no image. What is the solution to display the image? Thanks.
Main:
static void Main(string[] args)
{
//FOR IE
InternetExplorerOptions options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
IWebDriver driver = new InternetExplorerDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), options);
// end of IE driver
driver.Navigate().GoToUrl("https://www.google.com");
var screenshot = (driver as ITakesScreenshot).GetScreenshot();
//send email
SendEmail(screenshot.AsByteArray, "google", DateTime.Now);
driver.Close();
driver.Quit();
}
sendemail method
//write byte[] to email
static void SendEmail(byte[] stream, string pageName, DateTime screenshotTime)
{
byte[] image = stream;
Attachment att = new Attachment(new MemoryStream(stream), pageName);
att.ContentDisposition.Inline = true;
att.ContentId = Guid.NewGuid().ToString();
att.ContentType.MediaType = "image/png";
//send mail
SmtpClient client = new SmtpClient(myMailServer);
MailMessage mailMessage = new MailMessage();
mailMessage.IsBodyHtml = true;
mailMessage.From = new MailAddress(from);
mailMessage.To.Add(new MailAddress(to));
//send message
mailMessage.Subject = "Website Screenshot";
mailMessage.Body += "Website Name: " + pageName + Environment.NewLine + Environment.NewLine;
mailMessage.Body += "Screenshot Time: " + screenshotTime + Environment.NewLine + Environment.NewLine;
mailMessage.Body = String.Format( "<h3>Screenshot</h3>" + #"<img src=""cid:{0}"" />", att.ContentId);
mailMessage.Attachments.Add(att);
try
{
client.Send(mailMessage);
}
catch (Exception ex)
{
throw ex;
}
}
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
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);