C#如何从远程网站发送带有附件的电子邮件
本文关键字:电子邮件 网站 程网站 | 更新日期: 2023-09-27 18:29:34
注意:我对编程很陌生。
我可以从电脑上通过电子邮件发送附件,但如何通过互联网发送附件,例如: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");
}
}
您需要下载该文件并将其作为附件添加,就像您已经完成的那样。
有点像
string localFilename = @"c:'localpath'tofile.jpg";
using(WebClient client = new WebClient())
{
client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}
将下载该文件。
首先下载图像,然后只使用本地文件,或者使用流,直接在附件的构造函数中使用它。看见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));