2016-01-07 59 views
0

發送電子郵件(不得不重新發布這個,因爲我做了一件在原來非常愚蠢的......)C#如何使用附件從一個遠程網站

注:我很新的節目。

我可以通過電子郵件發送附件,但是如何通過interwebs發送附件,例如:http://blah.com/image.jpg而不是@「C:\ Users \ me \ pictures \ picture.jpg」?

在此先感謝。

這是我有:

class Program 
    { 
     public const string GMAIL_SERVER = "smtp.gmail.com"; 
     public const int PORT = 587; 

     static void Main(string[] args) 
     { 
      Console.WriteLine("Mail To:"); 
      MailAddress to = new MailAddress(Console.ReadLine()); 

      Console.WriteLine("Mail From:"); 
      MailAddress from = new MailAddress(Console.ReadLine()); 

      MailMessage mail = new MailMessage(from, to); 

      Console.WriteLine("Subject:"); 
      mail.Subject = Console.ReadLine(); 

      mail.Attachments.Add(new Attachment(@"C:\Users\me\pictures\picture.jpg")); 
      //Not sure how to send from a remote website... 

      Console.WriteLine("Your Message:"); 
      mail.Body = Console.ReadLine(); 

      SmtpClient smtp = new SmtpClient(GMAIL_SERVER, PORT); 
      smtp.Host = "smtp.gmail.com"; 
      smtp.Port = 587; 

      smtp.Credentials = new NetworkCredential(
       "myemail", "password"); 
      smtp.EnableSsl = true; 
      Console.WriteLine("Sending email... Please wait..."); 

      smtp.Send(mail); 
      Console.WriteLine("Finshed!\n"); 

     } 
    } 

回答

0

您將需要下載的文件,並將其添加爲附件因爲你已經做了。

財產以後像

string localFilename = @"c:\localpath\tofile.jpg"; 
using(WebClient client = new WebClient()) 
{ 
    client.DownloadFile("http://www.example.com/image.jpg", localFilename); 
} 

將下載的文件。

+0

謝謝!你爲我節省了很多時間和精神錯亂。像魅力一樣工作! – Jujucat

0

首先下載Image,然後使用本地文件,或使用Stream並直接在Attachment的構造器中使用它。請參閱https://msdn.microsoft.com/library/system.net.mail.attachment(v=vs.110).aspx。對於第一種方法,只需使用帶有.DownloadFile的WebClient。對於第二個,請嘗試:

WebClient client = new WebClient(); 
client.OpenReadCompleted += (s, e) => 
    { 
     // e.Result is your stream containing the image. 
    }; 
client.OpenReadAsync(new Uri(imageUrl)); 
+0

感謝您的回答! – Jujucat