How to hide inline images from mail attachment in c# - c#

I am using LinkedResource for send inline images. İf i send one image, its work fine but if send two or more inline images SMTP sending as an inline images also as an Attachment.
İf I remove adding attachment part, images will be unreachable in the inbox.
How to hide inline image from Attachment any idea?
Here my code
public void SendEmailWithImageTo(string subject, string toMail, string decrypt, List<string> imageNames, Template template, List<UploadFile> UploadFiles = null)
{
this.FromMail = new MailAddress(this.MailUser, this.DisplayName);
List<MailImageModel> mailImageModels = new List<MailImageModel>();
AlternateView avHtml;
LinkedResource inline;
Attachment att;
string mailBodyForInfoFormat = "";
string tempTemplate = template.HtmlContent;
tempTemplate = string.Format(tempTemplate, decrypt);
foreach (var item in imageNames)
{
string path = $#"{HttpRuntime.AppDomainAppPath}\Image\MailingImage\{item}";
avHtml = AlternateView.CreateAlternateViewFromString(tempTemplate, null, MediaTypeNames.Text.Html);
if (item.Contains("png"))
{
inline = new LinkedResource(path);
inline.ContentType =new ContentType("image/png");
}
else if (item.Contains("gif"))
{
inline = new LinkedResource(path, MediaTypeNames.Image.Gif);
}
else
{
inline = new LinkedResource(path, MediaTypeNames.Image.Jpeg);
}
inline.ContentId = "MyPic";
avHtml.LinkedResources.Add(inline);
att = new Attachment(path);
att.ContentDisposition.Inline = true;
tempTemplate = tempTemplate.Replace("{", "{{").Replace("}", "}}");
mailBodyForInfoFormat = string.Format(tempTemplate, att.ContentId);
MailImageModel mailImageModel = new MailImageModel
{
AttachPath = path,
AlternateView = avHtml
};
mailImageModels.Add(mailImageModel);
}
mailBodyForInfoFormat = mailImageModels.Count > 0 ? mailBodyForInfoFormat : tempTemplate;
using (MailMessage mm = new MailMessage())
{
mm.From = this.FromMail;
mm.Subject = subject;
mm.Body = mailBodyForInfoFormat;
mm.IsBodyHtml = true;
mm.To.Clear();
mm.Bcc.Clear();
mm.CC.Clear();
mm.To.Add(toMail);
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = UseSSL == "1" ? true : false;
if (RelayActive == "0")
{
smtp.Host = MailServer;
NetworkCredential NetworkCred = new NetworkCredential(this.MailUser, this.MailPassword);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = Convert.ToInt32(this.MailPort);
}
else
{
smtp.Host = RelayMailServer;
smtp.Port = Convert.ToInt32(this.RelayPort);
}
if (mailImageModels.Count > 0)
{
if (mailImageModels.Count != mm.Attachments.Count)
{
foreach (var item in mailImageModels)
{
mm.Attachments.Add(new Attachment(item.AttachPath));
mm.AlternateViews.Add(item.AlternateView);
}
}
}
if (UploadFiles.Count > 0)
{
foreach (var item in UploadFiles)
{
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(item.Path);
attachment.Name = item.FileName;
mm.Attachments.Add(attachment);
//mm.Attachments.Add(new Attachment(item.Path));
}
}
smtp.Send(mm);
smtp.Dispose();
}
}

Related

Is there any method In .net MVC to export database date in file not in local machine and send as file attachment with email.?

Here is My Export code.
public void ExportCSV_Employee(HttpPostedFileBase file )
{
var sb = new System.Text.StringBuilder();
var list = _context.ProductItems.ToList();
foreach (var item in list)
{
sb.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}\t{13}\t{14}\t{15}\t{16}\t{17}\t{18}\t{19}\t{20}\t{21}\t{22}\t{23}\t{24}\t{25}\r", item.ScanCode, item.Name, item.UnitRetail, item.UnitCost, item.DeptName, item.PriceGroup, item.ProductCode, item.Pcode, item.StateTax, item.MaxQty, item.Modified, item.AllowFoodStamps, item.LocalTax, item.Crv, item.MinAge, item.AllowDirectDept, item.IsNegative, item.DeptType, item.ItemCategoryId, item.ProductSubCategory, item.AllowFractionDept, item.BuyDown, item.UpcType, item.OverRide, item.PkgSize, item.Discount);
}
//mail method to send mail
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("mymail#gmail.com");
SmtpClient smtp = new SmtpClient();
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("mymail#gmail.com" , "password");
smtp.Host = "smtp.gmail.com";
//recipient address
mail.To.Add(new MailAddress("receiver#gmail.com"));
}
in this way, my mail sending work but I want to attach the date from my database as a start retrieving through StringBuilder. How can I attach my data as a file attachment with email?
var sb = new System.Text.StringBuilder();
var list = _context.ProductItems.ToList();
foreach (var item in list)
{
sb.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}\t{13}\t{14}\t{15}\t{16}\t{17}\t{18}\t{19}\t{20}\t{21}\t{22}\t{23}\t{24}\t{25}\r", item.ScanCode, item.Name, item.UnitRetail, item.UnitCost, item.DeptName, item.PriceGroup, item.ProductCode, item.Pcode, item.StateTax, item.MaxQty, item.Modified, item.AllowFoodStamps, item.LocalTax, item.Crv, item.MinAge, item.AllowDirectDept, item.IsNegative, item.DeptType, item.ItemCategoryId, item.ProductSubCategory, item.AllowFractionDept, item.BuyDown, item.UpcType, item.OverRide, item.PkgSize, item.Discount);
}
//Create a virtual file in memory
byte[] bytes = null;
using (var ms = new MemoryStream())
{
TextWriter tw = new StreamWriter(ms);
tw.Write(sb.Tostring());
tw.Flush();
ms.Position = 0;
bytes = ms.ToArray();
}
//Create Attachment
Attachment att = new Attachment(new MemoryStream(bytes), name);
//mail method to send mail
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("mymail#gmail.com");
SmtpClient smtp = new SmtpClient();
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("mymail#gmail.com" , "password");
smtp.Host = "smtp.gmail.com";
//recipient address
mail.To.Add(new MailAddress("receiver#gmail.com"));
//Add the attachment to the mail message
mail.Attachments.Add(data);
After spending some time I figure out the solution for this problem first save data in a Memorystream and then pass it to the email attachment method.
{
public void ExportCSV_Employee(HttpPostedFileBase file )
{
var sb = new System.Text.StringBuilder();
var list = _context.ProductItems.ToList();
foreach (var item in list)
{
sb.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}\t{13}\t{14}\t{15}\t{16}\t{17}\t{18}\t{19}\t{20}\t{21}\t{22}\t{23}\t{24}\t{25}\r", item.ScanCode, item.Name, item.UnitRetail, item.UnitCost, item.DeptName, item.PriceGroup, item.ProductCode, item.Pcode, item.StateTax, item.MaxQty, item.Modified, item.AllowFoodStamps, item.LocalTax, item.Crv, item.MinAge, item.AllowDirectDept, item.IsNegative, item.DeptType, item.ItemCategoryId, item.ProductSubCategory, item.AllowFractionDept, item.BuyDown, item.UpcType, item.OverRide, item.PkgSize, item.Discount);
}
//Storing data in virtual memory and then pass to email attachment
var myString = sb.ToString();
var myByteArray = System.Text.Encoding.UTF8.GetBytes(myString);
var ms = new MemoryStream(myByteArray);
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("mymail#gmail.com");
SmtpClient smtp = new SmtpClient();
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("mymail#gmail.com" , "password");
smtp.Host = "smtp.gmail.com";
//recipient address
mail.To.Add(new MailAddress("receiver#gmail.com"));
string Fname = "PriceBook.dat";
if ( ms!= null)
{
string fileName = Fname;
mail.Attachments.Add(new Attachment(ms, "fileName.dat", "text/dat"));
};
smtp.Send(mail);
}
}

"noname" attachment shown when email sent has image

HELP! So i have this issue wherein theres a "noname" attachment when sending emails with pictures as seen below
Now, i want this to remove since it is not part of my emailer.
heres is my code below
public static bool SendEmailNotification(List<string> toList, List<string> ccList, string subject, string body)
{
bool isSent = true;
try
{
var mail = new MailMessage();
var smtpClient = new SmtpClient(Constants.SMTP.SMTPClient);
var alternateView = AlternateView.CreateAlternateViewFromString(body, null, Constants.SMTP.Format);
mail.From = new MailAddress(Constants.SMTP.EmailAddress);
if (toList != null && toList.Any())
{
foreach (var email in toList)
{
mail.To.Add(email);
}
if (ccList != null && ccList.Any())
{
foreach (var email in ccList)
{
mail.CC.Add(email);
}
}
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.AlternateViews.Add(alternateView);
smtpClient.Credentials = new NetworkCredential(Constants.SMTP.EmailAddress,
Constants.SMTP.EmailPassword, Constants.SMTP.Email);
smtpClient.Send(mail);
}
else
{
isSent = false;
}
}
catch
{
isSent = false;
}
return isSent;
}
The attachment is actually your image payload in binary. It's set to "noname". Reason being is certain parameters aren't set properly. In this case, to do it properly refer to https://brutaldev.com/post/sending-html-e-mail-with-embedded-images-(the-correct-way)
if( attachementFile!=null)
{
Attachment attachment = new Attachment(attachementFile, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachementFile);
disposition.ModificationDate = File.GetLastWriteTime(attachementFile);
disposition.ReadDate = File.GetLastAccessTime(attachementFile);
disposition.FileName = Path.GetFileName(attachementFile);
disposition.Size = new FileInfo(attachementFile).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
return attachment;
}
Here's the code from the link in #kendolew's answer with an example on how to properly include an attachment:
public static void SendMessageWithEmbeddedImages()
{
string htmlMessage = #"<html>
<body>
<img src='cid:EmbeddedContent_1' />
</body>
</html>";
SmtpClient client = new SmtpClient("mail.server.com");
MailMessage msg = new MailMessage("noreply#deventerprise.net",
"someone#deventerprise.net");
// Create the HTML view
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
htmlMessage,
Encoding.UTF8,
MediaTypeNames.Text.Html);
// Create a plain text message for client that don't support HTML
AlternateView plainView = AlternateView.CreateAlternateViewFromString(
Regex.Replace(htmlMessage,
"<[^>]+?>",
string.Empty),
Encoding.UTF8,
MediaTypeNames.Text.Plain);
string mediaType = MediaTypeNames.Image.Jpeg;
LinkedResource img = new LinkedResource(#"C:\Images\MyImage.jpg", mediaType);
// Make sure you set all these values!!!
img.ContentId = "EmbeddedContent_1";
img.ContentType.MediaType = mediaType;
img.TransferEncoding = TransferEncoding.Base64;
img.ContentType.Name = img.ContentId;
img.ContentLink = new Uri("cid:" + img.ContentId);
htmlView.LinkedResources.Add(img);
//////////////////////////////////////////////////////////////
msg.AlternateViews.Add(plainView);
msg.AlternateViews.Add(htmlView);
msg.IsBodyHtml = true;
msg.Subject = "Some subject";
client.Send(msg);
}

Send email using asp.net, C#

in my web application I have a form to send an email to the group of people , i want to send a carbon copy but i have an exception that said :
The specified string is not in the form required for an e-mail address.
That is my code:
protected void SendButton_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.office365.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = from.Text;
string password = PassTextBox.Text;
string emailTo = toddl.SelectedValue.ToString();
string subject = subject_txt.Text;
string body = txtBody.Text;
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
MailAddress copy1 = new MailAddress(ccddl1.SelectedValue.ToString());
if(copy1!=null)
{
mail.CC.Add(copy1);
}
MailAddress copy2 = new MailAddress(ccddl2.SelectedValue.ToString());
if (copy2 != null)
{
mail.CC.Add(copy2);
}
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
if (syllabus_attach.HasFile)
{
string FileName = Path.GetFileName(syllabus_attach.PostedFile.FileName);
mail.Attachments.Add(new Attachment(syllabus_attach.PostedFile.InputStream, FileName));
}
if (course_exam_attach.HasFile)
{
string FileName = Path.GetFileName(course_exam_attach.PostedFile.FileName);
mail.Attachments.Add(new Attachment(course_exam_attach.PostedFile.InputStream, FileName));
}
if (answer_key_attach.HasFile)
{
string FileName = Path.GetFileName(answer_key_attach.PostedFile.FileName);
mail.Attachments.Add(new Attachment(answer_key_attach.PostedFile.InputStream, FileName));
}
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
string script = "alert(\"Request Sent Successfully!\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
}
You should change the CC code to
if(!String.IsNullOrWhitespace(ccddl1.SelectedValue.ToString())
{
mail.CC.Add(new MailAddress(ccddl1.SelectedValue.ToString());
}
if (!String.IsNullOrWhitespace(ccddl2.SelectedValue.ToString())
{
mail.CC.Add(new MailAddress(ccddl2.SelectedValue.ToString()));
}

SendMail in asp .net

using System.Net.Mail;
protected void SendMail()
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.google.com");
SmtpServer.Timeout = 30000;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
mail.From = new MailAddress("myemail#gmail.com");
mail.To.Add("recipient#gmail.com");
mail.Subject = "test";
mail.Body = "test";
mail.Priority = MailPriority.High;
SmtpServer.Port = 587;//25
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "pwd");
SmtpServer.EnableSsl = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Send(mail);
//MessageBox.Show("mail Send");
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message.ToString());
}
}
I have not found any error in my code as per several sources on internet. Still this is not working out.
Change you gmail Account Access
Sign in with your Google Account and redirect to this link
https://www.google.com/settings/security/lesssecureapps
Press the Enable, and try your code again
https://support.google.com/accounts/answer/6010255
Try this method
In Gmail Use Port-25 and SMTP-smtp.gmail.com
public void mail(string FromEmail, string FromPass, string To, string Tocc, string Tobcc, string subject, string message, string smtpadd, int portnum)
{
try
{
System.Net.Mail.SmtpClient st = new System.Net.Mail.SmtpClient(smtpadd);
System.Net.Mail.MailMessage mst = new System.Net.Mail.MailMessage();
mst.To.Add(To);
if (Tocc != "")
{
mst.CC.Add(Tocc);
}
if (Tobcc != "")
{
mst.Bcc.Add(Tobcc);
}
mst.IsBodyHtml = true;
mst.From = new System.Net.Mail.MailAddress(FromEmail);
mst.Subject = subject;
mst.Body = message;
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(FromEmail, FromPass);
st.UseDefaultCredentials = true;
st.EnableSsl = true;
st.Port = portnum;
st.Credentials = nc;
st.Send(mst);
}
catch (Exception e)
{
}
}

Send Email Using Smtp Client with Mandrill

I want to send a message using Mandrill.I need the following code to do this:
Send the same message to all recipient without Each one of them see the address of the other recipient.
I used the following code :
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
string[] toResult = to.Split(new Char[] { ';' });
foreach (string s in toResult)
{
if (s != null && !s.Trim().Equals("") && !string.IsNullOrEmpty(s))
{
message.Bcc.Add(s);
}
}
if (!cc.Equals(""))
{
string[] ccResult = cc.Split(new Char[] { ';' });
foreach (string s in ccResult)
{
message.CC.Add(s);
}
}
if (!cci.Equals(""))
{
string[] cciResult = cci.Split(new Char[] { ';' });
foreach (string s in cciResult)
{
message.Bcc.Add(s);
}
}
message.Subject = subject;
message.From = new System.Net.Mail.MailAddress(from, from);
message.IsBodyHtml = true;
message.Body = "<html><body>" + body + "</body></html>";
message.BodyEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString
(System.Text.RegularExpressions.Regex.Replace(body, #"<(.|\n)*?>", string.Empty), System.Text.Encoding.UTF8, "text/plain");
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, System.Text.Encoding.UTF8, "text/html");
message.AlternateViews.Add(plainView);
message.AlternateViews.Add(htmlView);
message.Priority = System.Net.Mail.MailPriority.Normal;
smtp.Host = smtpH;
bool ssl = false;
if (useSSL.Equals("true"))
ssl = true;
if (ssl)
{
smtp.EnableSsl = true;
}
else
{
smtp.EnableSsl = false;
}
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(userName, password);
smtp.Port = Convert.ToInt32(port);
message.Headers.Add("Message-Id", String.Concat("<", DateTime.Now.ToString("yyMMdd"), ".",
DateTime.Now.ToString("HHmmss"), "#" + from.Split('#')[1].ToString() + ">"));
smtp.Send(message);
As you can see in the code snippet above, I added all the emails in the Bcc collection, but it does not work.
Does anyone have any idea about this problem.
If people are still seeing each other's email address, you'll probably want to go to the Sending Defaults page in your account and disable the option to expose recipients to one another. Otherwise, you can add a custom SMTP header to turn that option off, but it sounds like you probably don't want that on by default.

Categories

Resources