我想发送包含多个文件附件的电子邮件。
我使用System.Web.Mail.MailMessage
,并在HttpFileCollection
中添加所有文件附件。
MailMessage msg = new MailMessage();
string body = BodyTextBox.Text;
string smtpServer = "mail.MySite.com";
string userName = "info@Mysite.com";
string password = "***";
int cdoBasic = 1;
int cdoSendUsingPort = 2;
if (userName.Length > 0)
{
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", smtpServer);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 25);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", cdoSendUsingPort);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", cdoBasic);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", userName);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password);
}
msg.To = "doc@Mysite.com";
msg.From = "info@Mysite.com";
msg.Subject = "Sent mail";
msg.Body = body;
if (fileUpload.HasFile)
{
int iUploadedCnt = 0;
HttpFileCollection hfc = Request.Files;
for (int i = 0; i <= hfc.Count - 1; i++) // CHECK THE FILE COUNT.
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath("Uploaded_Files\\") + Path.GetFileName(hpf.FileName));
msg.Attachments.Add(new MailAttachment(Server.MapPath("Uploaded_Files\\") + Path.GetFileName(hpf.FileName)));
}
}
}
msg.BodyEncoding = System.Text.Encoding.UTF8;
SmtpMail.SmtpServer = smtpServer;
SmtpMail.Send(msg);
没关系,但我不想在服务器中保存文件,我想发送邮件而不保存。
答案 0 :(得分:2)
使用System.Net.Mail.Attachment
类而不是System.Web.Mail.MailAttachment
类,您可以使用接受Stream
作为第一个参数的重载:
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
msg.Attachments.Add(new Attachment(hpf.InputStream, Path.GetFileName(hpf.FileName)));
}