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);
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 am trying to send email using C# but I am getting below error.
Mailbox was unavailable. The server response was: Relay access denied. Please authenticate.
I am not sure why I am getting this error. Here, I am using smtp2go third party to send this email.
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#wraptite.com");
mail.To.Add("test1#gmail.com");
mail.Subject = "Test Email";
mail.Body = "Report";
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password");
//SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
I've tried your code and it work fine.
But in my case, to use the smtp server, from(email address of sender) must use the same domain to authenticate.(but gmail is available to this Send emails from a different address or alias)
So, If your SMTP server connect to smtp2go.com, try as below.
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#smtp2go.com");
Or if you need to use service of smtp2go, it would be better use rest API.
Here is updated by your comment when using gmail.
Gmail required secure app access. that's a reason why code is not work.
So, there is two options for this.
1. Update your gmail account security
(origin idea from here : C# - 이메일 발송방법)
Go to here and turn on "Less secure app access". after doing this your code will work.(it works)
2. Using "Google API Client Library for .NET."
I think this is not so easy, check this out, I found an answer related with this here
#region SendMail
//Mail Setting
string EmailSubject = "EmailSubject";
string EmailBody = "EmailBody";
try
{
string FromAddress = "abc#gmail.com";
string EmailList = "abc1#gmail.com";
string EmailServer = "ipofemailserver";
using (var theMessage = new MailMessage(FromAddress, EmailList))
{
// Construct the alternate body as HTML.
string body = "EmailBody";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
theMessage.AlternateViews.Add(alternate);
theMessage.Subject = EmailSubject;
theMessage.IsBodyHtml = true;
SmtpClient theSmtpServer = new SmtpClient();
theSmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
theSmtpServer.Host = EmailServer;
theSmtpServer.Send(theMessage);
}
}
catch (Exception ex)
{
string AppPath = AppDomain.CurrentDomain.BaseDirectory;
string ErrorPath = AppDomain.CurrentDomain.BaseDirectory + "File\\Error\\";
string OutFileTime = DateTime.Now.ToString("yyyyMMdd");
using (StreamWriter sw = new StreamWriter(ErrorPath + OutFileTime + ".txt", true, System.Text.Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + ":");
sw.WriteLine(ex.ToString());
sw.Close();
}
}
#endregion
Hi I need to send an email using template in c# windows application . I had created a template but i am unable to pass the parameters through the html template. Here is the template which i am using.
For this HTML Template i am calling this in my windows application and sending through gmail smtp. I am able to send the mail but unable to pass the parameters into it. Please Help me out.Here is the code where i am calling in my windows application
try
{
using (StreamReader reader = File.OpenText("H:\\Visitor Management_Project\\Visitor Management_Project\\Visitor Management_Project\\EmailTemplate.htm"))
{
SmtpClient SmtpServer = new SmtpClient("173.194.67.108", 587);
SmtpServer.UseDefaultCredentials = false;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.Credentials = new System.Net.NetworkCredential("ambarishkesavarapu#gmail.com", "*******");
//SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
message = new MailMessage();
message.Subject = "Visitor Arrived";
//message.SubjectEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
message.Body = "EmailTemplate.htm";
//message.BodyEncoding = System.Text.Encoding.UTF8;
message.From = new MailAddress("ambarishkesavarapu#gmail.com");
message.To.Add(lblCPEmail.Text);
message.Priority = MailPriority.High;
message.Body = reader.ReadToEnd();
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
SmtpServer.Send(message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
How to add Parameters into HTML Template where i am getting all the parameters of that in the same page in Textboxes. Please help me out
I think you already discovered the answer yourself, but I will keep posting the answer instead.
In case you are using Windows Forms and not Windows Presentation Forms (The different only the design part and many new features that does not have on Windows Forms), what I have done is like this (to send email):
public void SendEmail(string _from, string _fromDisplayName, string _to, string _toDisplayName, string _subject, string _body, string _password)
{
try
{
SmtpClient _smtp = new SmtpClient();
MailMessage _message = new MailMessage();
_message.From = new MailAddress(_from, _fromDisplayName); // Your email address and your full name
_message.To.Add(new MailAddress(_to, _toDisplayName)); // The recipient email address and the recipient full name // Cannot be edited
_message.Subject = _subject; // The subject of the email
_message.Body = _body; // The body of the email
_smtp.Port = 587; // Google mail port
_smtp.Host = "smtp.gmail.com"; // Google mail address
_smtp.EnableSsl = true;
_smtp.UseDefaultCredentials = false;
_smtp.Credentials = new NetworkCredential(_from, _password); // Login the gmail using your email address and password
_smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
_smtp.Send(_message);
ShowMessageBox("Your message has been successfully sent.", "Success", 2);
}
catch (Exception ex)
{
ShowMessageBox("Message : " + ex.Message + "\n\nEither your e-mail or password incorrect. (Are you using Gmail account?)", "Error", 1);
}
}
And I am using it like this:
SendEmail(textBox2.Text, textBox5.Text, textBox3.Text, "YOUR_FULL_NAME", textBox4.Text, textBox6.Text, "YOUR_EMAIL_PASSWORD");
Here is the image:
May this answer would help you.
Cheers!
I have one form through which ,Sender text his email-id and password and selects attachment
using fileupload,recipients's email id i am getting from database table,email is reaching to recipients fine..but
problem is that when i attach a attachment ,attachment's size goes 0 except 1st email-id
,which i am getting from table....i have pasted code..
foreach (string email_to in list_emails)
{
MailMessage mail = new MailMessage();
mail.To.Add(email_to);
mail.Subject = "UPDATES FROM ATTENDANCE S/W";
mail.From = new MailAddress(txtFrom.Text.ToString());
mail.Body = txtMessage.Text;
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Attachment myAttachment =
new Attachment(FileUpload1.FileContent, fileName);
mail.Attachments.Add(myAttachment);
}
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(txtFrom.Text.ToString(), txtPasswd.Text.ToString());
smtp.EnableSsl = true;
smtp.Send(mail);
}
This is happening because FileContent is a Stream and so when you read from it the position of that Stream is left at the end. Consider something like this. At the top of the loop store the bytes, you don't need to keep reading them from the Stream anyway:
bool hasFile = FileUpload1.HasFile;
int fileLen = FileUpload1.PostedFile.ContentLength;
Stream stream = FileUpload1.FileContent;
byte[] file = new byte[fileLen];
stream.Read(file, 0, fileLen);
and then down in the loop, leverage the variable:
new Attachment(new MemoryStream(file) ...
and you'll want to change the if statement to leverage the bool:
if (hasFile)
Why can't I send xls,doc and other files - it does work for jpg,txt and others.
private void BuildAndSend(string pTo,string pCC,string pSubject,string pBody)
{
// building the mail
System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(pTo);
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("mymail#gmail.com");
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(fromAddress, toAddress);
mm.Subject = pSubject ;
mm.Body = pBody;
System.Net.Mail.MailAddress cc = new System.Net.Mail.MailAddress(pCC);
mm.CC.Add(cc);
addAttachments(mm);
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
//sending the mail
sendMail(mm);
}
private void addAttachments(System.Net.Mail.MailMessage mm)
{
string attachmentFile;
for (int i = 0; i < lstAttachments.Items.Count ; i++)
{
string fileFullName = pullDictionary[i];
attachmentFile = fileFullName;
System.Net.Mail.Attachment mailAttachment = new System.Net.Mail.Attachment(attachmentFile);
mm.Attachments.Add(mailAttachment);
}
}
private void sendMail(System.Net.Mail.MailMessage mm)
{
try
{
// loging in into sending user account
string smtpHost = "smtp.gmail.com";
string userName = "mymail#gmail.com";//sending Id
string password = "mypass";
System.Net.Mail.SmtpClient mClient = new System.Net.Mail.SmtpClient();
mClient.Port = 587;
mClient.EnableSsl = true;
mClient.UseDefaultCredentials = false;
mClient.Credentials = new NetworkCredential(userName, password);
mClient.Host = smtpHost;
mClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
mClient.Send(mm);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
if you can show me another way to send these files it will be great as well
If your jpegs and text files are going I'm guessing your problem may be in your path to some of the other file types or in the size of some of these other files (just a wild guess really as the code you posted looks ok).
// this looks suspect
string fileFullName = pullDictionary[i];
attachmentFile = fileFullName;
Here is a snippet of some working code. Note that I've never set either the mm.BodyEncoding = System.Text.Encoding.UTF8; or mClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; properties explicitly and have had success. (Probably just an unrelated observation...)
MailMessage m = new MailMessage(_gmailEmail, _to);
m.Subject = _emailSubject;
m.Body = _body;
for (int i = 0; i < lstAttachments.Items.Count ; i++) // your list
m.Attachments.Add(new Attachment("\path\to\file\to\attach\here"));
You mentioned that you'd like to see something different... Well, your attachment code looks fine so I thought I'd provide some code that allows you to embed images inline in your email rather than as an attachment:
// the below adds embedded images an email...
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(
_body, null, System.Net.Mime.MediaTypeNames.Text.Html);
LinkedResource pic = new LinkedResource("\path\to\file\to\embed\here", System.Net.Mime.MediaTypeNames.Image.Jpeg);
pic.ContentId = "IMAGE1"; // just make sure this is a unique string if you have > 1
avHtml.LinkedResources.Add(pic);
m.AlternateViews.Add(avHtml);
Post some specific error messages/exceptions caught and you'll get more help...