2014-01-18 3 views
1

여러 첨부 파일이있는 이메일을 보내려고합니다.먼저 저장하지 않고 HttpFileCollection을 사용하여 여러 첨부 파일이있는 메일 보내기

나는 System.Web.Mail.MailMessage을 사용하고 모든 첨부 파일을 HttpFileCollection에 추가합니다.

MailMessage msg = new MailMessage(); 
string body = BodyTextBox.Text; 
string smtpServer = "mail.MySite.com"; 
string userName = "[email protected]"; 
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 = "[email protected]"; 
msg.From = "[email protected]"; 
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

는 이메일 클라이언트 나 서버에서 전송되는가? 또는 서버에 첨부 파일을 보내도 괜찮습니까? 그렇지만 저장할 필요가 없습니까? – klarki

+0

예, 서버에서 보내지 만 파일을 저장하지 않으려합니다. 'hpf.SaveAs (Server.MapPath ("Uploaded_Files \\") + Path.GetFileName (hpf.FileName));'. 첨부 파일을 서버에 저장하는 것을 추가하고 싶습니다. –

+0

응용 프로그램에서 임시 저장을 할 수 있으며 파일을 보낸 후에 해당 파일을 응용 프로그램에서 삭제합니다. –

답변

2

대신 System.Web.Mail.MailAttachment 클래스의 System.Net.Mail.Attachment 클래스를 사용하여 첫 번째 인수로 Stream 받아 과부하 사용할 수 있습니다

HttpPostedFile hpf = hfc[i]; 
if (hpf.ContentLength > 0) 
{  
    msg.Attachments.Add(new Attachment(hpf.InputStream, Path.GetFileName(hpf.FileName))); 
} 
관련 문제