Send Uploaded File as attachment - c#

I am trying to get an uploaded file to be sent as an attachment in my ashx file. Here is the code I am using:
HttpPostedFile fileupload = context.Request.Files[0];
//filename w/o the path
string file = Path.GetFileName(fileupload.FileName);
MailMessage message = new MailMessage();
//*****useless stuff********
message.To.Add("abc#xxx.com");
message.Subject = "test";
message.From = new MailAddress("test#aaa.com");
message.IsBodyHtml = true;
message.Body = "testing";
//*****useless stuff********
//Fault line
message.Attachments.Add(new Attachment(file, MediaTypeNames.Application.Octet))
//Send mail
SmtpClient smtp = new System.Net.Mail.SmtpClient("xxxx", 25);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("xxx", "xxxx");
smtp.Send(message);
I am able to send the email without the attachment.
Do I need to save the file first and then add to attachment?

You do NOT need to, nor should you, save attachments to the server unnecessarily. ASP Snippets has an article on how to do it in ASP.NET WebForms.
Doing it in C# MVC is even nicer:
public IEnumerable<HttpPostedFileBase> UploadedFiles { get; set; }
var mailMessage = new MailMessage();
// ... To, Subject, Body, etc
foreach (var file in UploadedFiles)
{
if (file != null && file.ContentLength > 0)
{
try
{
string fileName = Path.GetFileName(file.FileName);
var attachment = new Attachment(file.InputStream, fileName);
mailMessage.Attachments.Add(attachment);
}
catch(Exception) { }
}
}

Following in the footsteps of Serj Sagan, here's a handler using webforms, but with <input type="file" name="upload_your_file" /> instead of the <asp:FileUpload> control:
HttpPostedFile file = Request.Files["upload_your_file"];
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
var attachment = new Attachment(file.InputStream, fileName);
mailMessage.Attachments.Add(attachment);
}
This is useful if you don't need (or can't add) a runat="server" on your form tag.

You can do like this:
private void btnSend_Click(object sender,EventArgs e)
{
MailMessage myMail = new MailMessage();
myMail.To = this.txtTo.Text;
myMail.From = "<" + this.txtFromEmail.Text + ">" + this.txtFromName.Text;
myMail.Subject = this.txtSubject.Text;
myMail.BodyFormat = MailFormat.Html;
myMail.Body = this.txtDescription.Text.Replace("\n","<br>");
//*** Files 1 ***//
if(this.fiUpload1.HasFile)
{
this.fiUpload1.SaveAs(Server.MapPath("MyAttach/"+fiUpload1.FileName));
myMail.Attachments.Add(new MailAttachment(Server.MapPath("MyAttach/"+fiUpload1.FileName)));
}
//*** Files 2 ***//
if(this.fiUpload2.HasFile)
{
this.fiUpload2.SaveAs(Server.MapPath("MyAttach/"+fiUpload2.FileName));
myMail.Attachments.Add(new MailAttachment(Server.MapPath("MyAttach/"+fiUpload2.FileName)));
}
SmtpMail.Send(myMail);
myMail = null;
this.pnlForm.Visible = false;
this.lblText.Text = "Mail Sending.";
}

FileName is the name of the file on the client, not on the server. You will need to use SaveAs or the InputStream to get any content into the attachment.
Here is a link to the MSDN documentation.

Related

Sending email with attachment of zip folder not attaching the zip folder

I am trying to attach a zip file after downloading files from the server and then sending them in an email.
Here is where i am downloading the files:
else if (radio[0] == "Email Statements")
{
// Make array of emails into List for sending in email
if (emails.ToString() != "")
{
var allEmails = emails[0].Split(',');
foreach (var email in allEmails)
{
if (emailValid.IsMatch(email))
{
everyEmail.Add(email);
}
else
{
return Json(new { success = false, message = $"* Not valid email address: {email}.\n\n * Please double check and try again." });
}
List<string> distinctFiles = allPaths
.GroupBy(x => x.Split(new char[] { '\\' }).Last())
.Select(x => x.First())
.ToList();
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(distinctFiles, #"\");
MemoryStream output = new MemoryStream();
zip.Save(output);
//return File(output.ToArray(), "application/zip");
DBQueries.SendEmail(everyEmail, output, fromAddress, "Client Statement Reports", "Here are your requested Client Statements", true);
}
Then the DBQueries.SendEmail function will send me here and this is where I am having trouble. How can I get my downloaded files to this function correctly?
public static void SendEmail(List<string> recipients, MemoryStream output, string from, string subject, string htmlMessage, bool isHtml = true)
{
var host = ConfigurationManager.AppSettings["emailHost"];
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(from);
foreach (var r in recipients)
{
mail.To.Add(r);
}
mail.Subject = subject;
mail.IsBodyHtml = isHtml;
mail.Body = htmlMessage;
//string result = System.Text.Encoding.UTF8.GetString(output.ToArray());
SmtpClient SmtpServer = new SmtpClient(host);
SmtpServer.Port = 25;
Attachment myZip = new Attachment(output);
mail.Attachments.Add(myZip);
SmtpServer.Send(mail);
}

Break apart email attachment if zip is too big to email

So I can send up to 25MB in an email attachment. I am looking for away to check how big the file size is and if its too big break it apart and send in two emails. (Or if there is a better way to do it)?
Here is where I am sending the email with the attachment:
public static void SendEmail(List<string> recipients, MemoryStream output, string from, string subject, string htmlMessage, bool isHtml = true)
{
var host = ConfigurationManager.AppSettings["emailHost"];
var emailFrom = ConfigurationManager.AppSettings["FromEmail"];
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(from);
foreach (var r in recipients)
{
mail.To.Add(r);
}
mail.Subject = subject;
mail.IsBodyHtml = isHtml;
mail.Body = htmlMessage;
//string result = System.Text.Encoding.UTF8.GetString(output.ToArray());
SmtpClient SmtpServer = new SmtpClient(host);
SmtpServer.Port = 25;
Attachment myZip = new Attachment(output, "ClientStatements.zip");
mail.Attachments.Add(myZip);
SmtpServer.Send(mail);
}
catch (Exception ex)
{
FMBUtilities.Logger.LogErrorToSql2012PrdAndEmailTeam("DBQueries", "SendEmail", ex);
}
}
Here is where i am creating the zip file to send:
if (emails.ToString() != "")
{
var allEmails = emails[0].Split(',');
foreach (var email in allEmails)
{
if (emailValid.IsMatch(email))
{
everyEmail.Add(email);
}
else
{
return Json(new { success = false, message = $"* Not valid email address: {email}.\n\n * Please double check and try again." });
}
}
MemoryStream output = new MemoryStream();
List<string> distinctFiles = allPaths
.GroupBy(x => x.Split(new char[] { '\\' }).Last())
.Select(x => x.First())
.ToList();
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(distinctFiles, #"\");
zip.Save(output);
output.Position = 0;
DBQueries.SendEmail(everyEmail, output, fromAddress, "Client Statement Reports", "Here are your requested Client Statements", true);
}
I have found some things about setting the file size in the web.config file and things of that sort but just dont know the best way to go about this.

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

Image path in Xamarin.Android

I want to send a mail in xamarin.android.I can send as text with the code below without image but the problem occurs when i try to send with an image as logo. I mean, i can't find the path of the image.
My sending mail method is:
public static void SendMail(List<string> to, List<string> cc, string subject, string body,string mfrom)
{
string messageHeader = "Android E-Mail Testi";
MailMessage msg = new MailMessage();
msg.From = new MailAddress(mfrom);
msg.To.Add(new MailAddress(to[0]));
msg.CC.Add(new MailAddress(cc[0]));
var inlineLogo = new LinkedResource("Drawable://logo.png");//This path is not working.
inlineLogo.ContentId = Guid.NewGuid().ToString();
msg.Body = string.Format(#"<img class=""img-responsive"" src=""cid:{0}"" style=""width:25%; float:left""/>
<br/><br/><h3>" + messageHeader + #"</h3>" + body, inlineLogo.ContentId);
var view = AlternateView.CreateAlternateViewFromString(msg.Body, null, "text/html");
view.LinkedResources.Add(inlineLogo);
msg.AlternateViews.Add(view);
msg.IsBodyHtml = true;
msg.Subject = subject;
msg.SubjectEncoding = Encoding.UTF8;
SmtpClient smtpClient = new SmtpClient("xx.xxx.x.xxx");
msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
List<MemoryStream> mStreams = null;
msg.BodyEncoding = Encoding.Unicode;
smtpClient.Send(msg);
if (mStreams != null)
foreach (MemoryStream mStream in mStreams)
mStream.Close();
}
I can send mail by using this code in asp.net.Only difference is file path. I used it like that and it works for web development:
var inlineLogo = new LinkedResource(HostingEnvironment.MapPath("~/images/logo.png"));
Which method should i use for image(logo.png) path in xamarin?
var inlineLogo = new LinkedResource(???);
I don't know the real path.How can i reach the path of the image in the drawable folder of the Resources folder?
Directory is:
Maybe it will help you. I created ToolbarItem with icon from the same folder Resources/drawable in such way:
new ToolbarItem("ToolbarItemName", "iconName.png", () => { //Some action; })

C# Sending Email with attached file (image)

My method sends an email using a SMTP Relay Server.
Everything works fine (the email gets sent), except for that the attached file (the image) is somehow compressed/notexistent and not able to retrieve from the email.
The method looks like this:
public static bool SendEmail(HttpPostedFileBase uploadedImage)
{
try
{
var message = new MailMessage() //To/From address
{
Subject = "This is subject."
Body = "This is text."
};
if (uploadedImage != null && uploadedImage.ContentLength > 0)
{
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(uploadedImage.InputStream, uploadedImage.FileName);
message.Attachments.Add(attachment);
}
message.IsBodyHtml = true;
var smtpClient = new SmtpClient();
//SMTP Credentials
smtpClient.Send(message);
return true;
}
catch (Exception ex)
{
//Logg exception
return false;
}
}
The uploadedImage is not null.
ContentLength is 1038946 bytes (correct size).
However, the email that is being sent contains the image as an attachment with correct filename, although it's size is 0 bytes.
What am I missing?
The second parameter of constructor of System.Net.Mail.Attachment is not the file name. It's the content type.
And perhaps ensure your stream position is 0 before to create attachment
#ChrisRun,
You should change the parameter HttpPostedFileBase as byte[] for example. This way you could re-use your class in more places.
Try changing FileName for ContentType and add the MediaTypeNames.Image.Jpeg.
Also, add the using directive for dispose the MailMessage and SmtpClient
using (var message = new MailMessage
{
From = new MailAddress("from#gmail.com"),
Subject = "This is subject.",
Body = "This is text.",
IsBodyHtml = true,
To = { "to#someDomain.com" }
})
{
if (imageFile != null && imageFile.ContentLength > 0)
{
message.Attachments.Add(new Attachment(imageFile.InputStream, imageFile.ContentType, MediaTypeNames.Image.Jpeg));
}
using (var client = new SmtpClient("smtp.gmail.com")
{
Credentials = new System.Net.NetworkCredential("user", "password"),
EnableSsl = true
})
{
client.Send(message);
}
}
Cheers

Categories

Resources