Programatically attaching document(s) to an email in asp.net
I am generating an email via codebehind in C# in my asp.net application using the line below:
ClientScript.RegisterStartupScript(this.GetType(), "FormLoading", "window.open('mailto:AccountsPayable@xyzCorp.com?subject=Invoice for ABC Corp - " + ddlJobCode.SelectedItem.Text + " - Supporting Documentation', 'email');", true);
Is it possible to include an attachment programatically as well (if the user points to the attachment documen开发者_如何学JAVAt via a browse button) ?
No I don't think so... the mailto
functionality is passed off by the browser to the default client. You have no other mechanism of talking to the client or even knowing if the mailto
was even successful.
If you want to add an attachment you will most likely have to send the email on behalf of them and do it server side.
Edit: To do it server side you would need to post the page so that the Browse
button pulls down the file server side and then you would need to construct the email and send it out via your own smtp server. Here is a quick code example, you will probably need to adapt it to work with your specific case:
In your server side OnClick
handler:
protected void btnSendEmail_Click(object sender, EventArgs e)
{
// this will get the file from your asp:FileUpload control (browse button)
HttpPostedFile file = (HttpPostedFile)(fuAttachment.PostedFile);
if ((file != null) && (file.ContentLength > 0))
{
// You should probably check file size and extension types and whatever
// other validation here as well
byte[] uploadedFile = new byte[file.ContentLength];
file.InputStream.Read(uploadedFile, 0, file.ContentLength);
// Save the file locally
int lastSlash = file.FileName.LastIndexOf('\\') + 1;
string fileName = file.FileName.Substring(lastSlash,
file.FileName.Length - lastSlash);
string localSaveLocation = yourLocalPathToSaveFile + fileName;
System.IO.File.WriteAllBytes(localSaveLocation, uploadedFile);
try
{
// Create and send the email
MailMessage msg = new MailMessage();
msg.To = "someone@somewhere.com";
msg.From = "somebody@somebody.com";
msg.Subject = "Attachment Test";
msg.Body = "Test Attachment";
msg.Attachments.Add(new MailAttachment(localSaveLocation));
// Don't forget you have to setup your SMTP settings
SmtpMail.Send(msg);
}
finally
{
// make sure to clean up the file that was uploaded
System.IO.File.Delete(localSaveLocation);
}
}
}
Not using the mailto method no, since it doesn't have any options for attachments.
You could have the user fill out a form which will create and send the email on the server side allowing you to add attachments and much more (in my opinion this is also more professional than mailto links which don't really support people using webmail services) However, this would then send the email through your server's email service, rather than the one the client would use.
精彩评论