using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
namespace AzureSendGridDemo
{
class Program
{
static void Main(string[] args)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("FromAddress", "Name");
msg.To.Add(new MailAddress("ToAddress", "Name"));
msg.Subject = "Mail from Azure and SendGrid!";
msg.Body = "This is just a simple test message!";
msg.IsBodyHtml = true;
msg.Attachments.Add("D:\image.jpg"); // if i put local path, it works.
msg.Attachments.Add(new Attachment(@"https://images-na.ssl-images-amazon.com/images/I/71nTxKhiqrL._UL1500_.jpg")); // if i put global path it doesn't works. It shows some errors are shown below:
//Sendgrid credentials for sending mail using smtpclient wrapper class.
SmtpClient client = new SmtpClient("smtp.sendgrid.net", 587);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("Username", "Password");
client.Send(msg);
Console.Read();
}
}
}
如果我使用的是全局路径,则会在我的控制台应用程序中显示错误:
未处理的异常:System.NotSupportedException:不支持给定路径的格式。 在System.IO.Path.GetFullPath(String path) 在System.IO.FileStream..ctor(字符串路径,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,FileOptions选项) 在System.IO.FileStream..ctor(字符串路径,FileMode模式,FileAccess访问,FileShare共享) 在System.Net.Mail.AttachmentBase.SetContentFromFile(String fileName,String mediaType) 在System.Net.Mail.AttachmentBase..ctor(String fileName) 在System.Net.Mail.Attachment..ctor(String fileName) 在E:\ SendGrid \ AzureSendGridDemo \ AzureSendGridDemo \ Program.cs中的AzureSendGridDemo.Program.Main(String [] args):第41行 按任意键继续 。 。
答案 0 :(得分:1)
这是因为您无法将URL传递给附件等电子邮件。
URL是您可以放在邮件正文中的链接,或者您也可以使用WebClient类C#下载文档并将其附加到电子邮件中。
答案 1 :(得分:1)
Attachment
构造函数没有重载,允许您传递url字符串。虽然有一个接受Stream
,但你可以这样做......
var imageRequest = HttpWebRequest.Create("https://images-na.ssl-images-amazon.com/images/I/71nTxKhiqrL._UL1500_.jpg")
using (var imageStream = imageRequest.GetResponse().GetResponseStream())
{
var x = new Attachment(imageStream, "image/jpeg");
}