Отправка почты вместе со встроенным изображением с помощью asp.net
отправка почты вместе со встроенным изображением с помощью asp.net
Я уже использовал следующий, но он не может работать
Dim EM As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage(txtFrom.Text, txtTo.Text)
Dim A As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(txtImagePath.Text)
Dim RGen As Random = New Random()
A.ContentId = RGen.Next(100000, 9999999).ToString()
EM.Attachments.Add(A)
EM.Subject = txtSubject.Text
EM.Body = "<body>" + txtBody.Text + "<br><img src='cid:" + A.ContentId +"'></body>"
EM.IsBodyHtml = True
Dim SC As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient(txtSMTPServer.Text)
SC.Send(EM)
Ответы
Ответ 1
Если вы используете .NET 2 или выше, вы можете использовать классы AlternateView и LinkedResource следующим образом:
string html = @"<html><body><img src=""cid:YourPictureId""></body></html>";
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
LinkedResource yourPictureRes = new LinkedResource("yourPicture.jpg", MediaTypeNames.Image.Jpeg);
yourPictureRes.ContentId = "YourPictureId";
altView.LinkedResources.Add(yourPictureRes);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(altView);
Надеюсь, вы можете вывести эквивалент VB.
Ответ 2
После того, как поиск и попытка должны состоять из четырех или пяти "ответов", я чувствовал, что мне нужно поделиться тем, что, как я понял, действительно работает, так как многие люди, похоже, не знают, как это сделать, или некоторые из них дают подробные ответы, которые многие другие имеют проблемы с, плюс несколько делают и дают только отрывочный ответ, который затем должен интерпретироваться. Поскольку у меня нет блога, но я хотел бы помочь другим, вот полный код, чтобы сделать все это. Большое спасибо Алексу Пеку, так как его ответ расширился.
inMy.aspx файл asp.net
<div>
<asp:LinkButton ID="emailTestLnkBtn" runat="server" OnClick="sendHTMLEmail">testemail</asp:LinkButton>
</div>
inMy.aspx.cs код за файлом С#
protected void sendHTMLEmail(object s, EventArgs e)
{
/* adapted from http://stackoverflow.com/info/1113345/sending-mail-along-with-embedded-image-using-asp-net
and http://stackoverflow.com/info/886728/generating-html-email-body-in-c-sharp */
string myTestReceivingEmail = "[email protected]"; // your Email address for testing or the person who you are sending the text to.
string subject = "This is the subject line";
string firstName = "John";
string mobileNo = "07711 111111";
// Create the message.
var from = new MailAddress("[email protected]", "displayed from Name");
var to = new MailAddress(myTestReceivingEmail, "person emailing to displayed Name");
var mail = new MailMessage(from, to);
mail.Subject = subject;
// Perform replacements on the HTML file (which you're using as a template).
var reader = new StreamReader(@"c:\Temp\HTMLfile.htm");
string body = reader.ReadToEnd().Replace("%TEMPLATE_TOKEN1%", firstName).Replace("%TEMPLATE_TOKEN2%", mobileNo); // and so on as needed...
// replaced this line with imported reader so can use a templete ....
//string html = body; //"<html><body>Text here <br/>- picture here <br /><br /><img src=""cid:SACP_logo_sml.jpg""></body></html>";
// Create an alternate view and add it to the email. Can implement an if statement to decide which view to add //
AlternateView altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
// Logo 1 //
string imageSource = (Server.MapPath("") + "\\logo_sml.jpg");
LinkedResource PictureRes = new LinkedResource(imageSource, MediaTypeNames.Image.Jpeg);
PictureRes.ContentId = "logo_sml.jpg";
altView.LinkedResources.Add(PictureRes);
// Logo 2 //
string imageSource2 = (Server.MapPath("") + "\\booking_btn.jpg");
LinkedResource PictureRes2 = new LinkedResource(imageSource2, MediaTypeNames.Image.Jpeg);
PictureRes2.ContentId = "booking_btn.jpg";
altView.LinkedResources.Add(PictureRes2);
mail.AlternateViews.Add(altView);
// Send the email (using Web.Config file to store email Network link, etc.)
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(mail);
}
HTMLfile.htm
<html>
<body>
<img src="cid:logo_sml.jpg">
<br />
Hi %TEMPLATE_TOKEN1% .
<br />
<br/>
Your mobile no is %TEMPLATE_TOKEN2%
<br />
<br />
<img src="cid:booking_btn.jpg">
</body>
</html>
в вашем файле Web.Config, внутри вашего <configuration> block вам нужно следующее, чтобы разрешить тестирование в папке TempMail на вашем диске c:\
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory" from="[email protected]">
<specifiedPickupDirectory pickupDirectoryLocation="C:\TempMail"/>
</smtp>
</mailSettings>
</system.net>
единственные другие вещи, которые вам понадобятся в верхней части вашего файла aspx.cs за файлом, включают в себя использование системы (если я пропустил один из них, вы просто щелкните правой кнопкой мыши на неизвестном классе и выберите вариант "Разрешить" )
using System.Net.Mail;
using System.Text;
using System.Reflection;
using System.Net.Mime; // need for mail message and text encoding
using System.IO;
Надеюсь, это поможет кому-то и большое спасибо вышеуказанному плакату за то, что он дал ответ, необходимый для выполнения работы (а также другую ссылку в моем коде).
Он работает, но я открыт для улучшений.
приветствий.