我需要从网上下载文本文件并在发送之前将其附加到邮件中。以下是我所做的但它抛出异常`发送邮件失败。该请求被曝光'
WebRequest request = FtpWebRequest.Create("http://samplesite/sampletext.txt"));
request.Credentials = new NetworkCredential("admin", "admin");
using (WebResponse response = request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
msg.Attachments.Add(new Attachment(responseStream, dictIterator.Key)); //on commenting this, it works fine
}
client.Send(msg); //throws exception
我确定它与附件有关,因为它可以使其正常工作。
答案 0 :(得分:0)
您正在处理响应对象,然后再从其流中读取和使用它。我没有测试代码,但这是一个简单的想法如何使用它:
byte[] myResponse;
using (WebResponse response = request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
myResponse = ReadFully(responseStream);//done with the stream now and dispose it
msg.Attachments.Add(new Attachment(Encoding.ASCII.GetString(myResponse), dictIterator.Key));
}
client.Send(msg);
答案 1 :(得分:0)
试试这段代码:
SmtpClient client=new SmtpClient( );
client.Credentials = new NetworkCredential("username", "password");
MailMessage msg = new MailMessage();
client.Host = "yourHost";
msg.From =new MailAddress( "adress-from");
msg.To.Add( new MailAddress("adress-to" ));
msg.Subject = "your subject";
msg.Body="your message";
System.Net.WebRequest myrequest;
System.Net.WebResponse myresponse;
System.IO.Stream s;
string url = "your url to the file";
myrequest = System.Net.WebRequest.Create(url);
myresponse = myrequest.GetResponse();
s = myresponse.GetResponseStream();
msg.Attachments.Add(new Attachment( s,System.Net.Mime.MediaTypeNames.Text.Plain));
client.Send(msg);