我需要从网络下载一个文本文件并将其附加到邮件中,然后再发送出去。下面是我所做的,但它抛出异常"发送邮件失败。请求被驳回"
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
我确定这与附件有关,因为评论它可以正常工作。
在从
响应对象的流中读取和使用响应对象之前,您正在释放响应对象。我还没有测试过代码,但这是如何使用它的简单想法:
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);
试试这段代码:
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);