我的方法使用SMTP中继服务器发送电子邮件。
一切都很好(电子邮件被发送),除了附件(图像)以某种方式被压缩/不存在,并且无法从电子邮件中检索
方法如下:
public static bool SendEmail(HttpPostedFileBase uploadedImage)
{
try
{
var message = new MailMessage() //To/From address
{
Subject = "This is subject."
Body = "This is text."
};
if (uploadedImage != null && uploadedImage.ContentLength > 0)
{
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(uploadedImage.InputStream, uploadedImage.FileName);
message.Attachments.Add(attachment);
}
message.IsBodyHtml = true;
var smtpClient = new SmtpClient();
//SMTP Credentials
smtpClient.Send(message);
return true;
}
catch (Exception ex)
{
//Logg exception
return false;
}
}
- uploadedImage不为null
- ContentLength为1038946字节(正确大小)
但是,正在发送的电子邮件将图像作为具有正确文件名的附件包含,尽管其大小为0字节
我错过了什么?
System.Net.Mail.Attachment
构造函数的第二个参数不是文件名。这是内容类型。也许在创建附件之前确保您的流位置为0
@ChrisRun,
- 例如,您应该将参数HttpPostedFileBase更改为byte[]。这样你就可以在更多的地方重复使用你的课
- 尝试更改ContentType的FileName并添加MediaTypeNames.Image.Jpeg
-
此外,添加用于处理MailMessage和SmtpClient 的using指令
using (var message = new MailMessage { From = new MailAddress("from@gmail.com"), Subject = "This is subject.", Body = "This is text.", IsBodyHtml = true, To = { "to@someDomain.com" } }) { if (imageFile != null && imageFile.ContentLength > 0) { message.Attachments.Add(new Attachment(imageFile.InputStream, imageFile.ContentType, MediaTypeNames.Image.Jpeg)); } using (var client = new SmtpClient("smtp.gmail.com") { Credentials = new System.Net.NetworkCredential("user", "password"), EnableSsl = true }) { client.Send(message); } }
干杯