I have a project requirement that we need to attach an HTML formatted log sheet to an email that gets sent to a user. I don't want the log sheet to be part of the body. I'd rather not use HTMLTextWriter or StringBuilder because the log sheet is quite complex.
Is there another method that I'm not mentioning or a tool that would make this easier?
Note: I've worked with the MailDefinition class and created a template but I haven't found a way to make this an attachment if that's even possible.
Since you're using WebForms, I would recommend rendering your log sheet in a Control as a string, and then attaching that to a MailMessage.
The rendering part would look a bit like this:
public static string GetRenderedHtml(this Control control)
{
StringBuilder sbHtml = new StringBuilder();
using (StringWriter stringWriter = new StringWriter(sbHtml))
using (HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter))
{
control.RenderControl(textWriter);
}
return sbHtml.ToString();
}
If you have editable controls (TextBox, DropDownList, etc), you'll need to replace them with Labels or Literals before calling GetRenderedHtml(). See this blog post for a complete example.
Here's the MSDN example for attachments:
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
"ben#contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
You can use Razor for email templates. RazorEngine or MvcMailer might do the job for you
Use Razor views as email templates inside a Web Forms app
Razor views as email templates
http://www.codeproject.com/Articles/145629/Announcing-MvcMailer-Send-Emails-Using-ASP-NET-MVC
http://kazimanzurrashid.com/posts/use-razor-for-email-template-outside-asp-dot-net-mvc
Related
This question already has answers here:
MimeKit add attachments to a message loaded from mht file
(2 answers)
Closed last month.
Is there any general way to add an attachment to a mail read from an stream using MimeKit?
I need something like this
var message = MimeMessage.Load(inputStream);
var newMessage = AddSomeInfoAttachment(message);
newMessage.WriteTo(outputStream)
The part in question is "AddSomeInfoAttachment(message)". The attachment (for now) is just a text file (a string in fact).
It appears to be easy if you create a new message (http://www.mimekit.net/docs/html/Creating-Messages.htm) but I suspect that it's way more complicated to start with an already created one (for instance: Where in the MIME tree is supposed to go the attachment? Do I have to copy all other parts to a newMessage or can I just modify the original message in place?)
So far the only "Attachments" collections (with an Add) I see is using a BodyBuilder and I suspect that is not that easy with an already loaded MimeMessage.
In the most common scenario, the following code snippet should do what you want/expect:
var message = MimeMessage.Load(fileName);
var attachment = new TextPart("plain") {
FileName = "attachment.txt",
ContentTransferEncoding = ContentEncoding.Base64,
Text = attachmentText
};
if (!(message.Body is Multipart multipart &&
multipart.ContentType.Matches("multipart", "mixed"))) {
// The top-level MIME part is not a multipart/mixed.
//
// Attachments are typically added to a multipart/mixed
// container which tends to be the top-level MIME part
// of the message (unless it is signed or encrypted).
//
// If the message is signed or encrypted, though, we do
// do not want to mess with the structure, so the correct
// thing to do there is to encapsulate the top-level part
// in a multipart/mixed just like we are going to do anyway.
multipart = new Multipart("mixed");
// Replace the message body with the multipart/mixed and
// add the old message body to it.
multipart.Add(message.Body);
message.Body = multipart;
}
// Add the attachment.
multipart.Add(attachment);
// Save the message back out to disk.
message.WriteTo(newFileName);
I'm using redemption to create a custom mail item and save it in the draft folder of my outlook. Currently the mailItem is saved in HTML format. I want to be able to save it in rtf Format. How can I do that ?
Here is the code I am using :
Redemption.RDOSession session = new Redemption.RDOSession();
session.MAPIOBJECT = olApp.Session.MAPIOBJECT;
Redemption.RDOFolder rFolder = session.GetDefaultFolder(Redemption.rdoDefaultFolders.olFolderDrafts);
Redemption.RDOMail rMsg = rFolder.Items.Add("ipm.note.mep");
// modify some custom fields ...
rMsg.BodyFormat = 3;
rMsg.Save();
Outlook.MailItem oMep = olApp.Session.GetItemFromID(rMsg.EntryID);
oMep.BodyFormat = Outlook.OlBodyFormat.olFormatRichText;
oMep.Display(false);
Changing the bodyFormat doesn't seem to work. I also tried the saveAs method with no success. I can change the format manually when the mailItem is open, but I want to do that automatically within my C# code.
Have you tried to set the RDOMail.RtfBody property?
I want to mail an asp.net page from c#. well it is questioned widely and I saw bulk of questions like that on stackoverflow too. But I have few problems that I'm not getting the solutions
What Itried
many example. below are few
using (System.IO.StreamReader reader = System.IO.File.OpenText( Server.MapPath("~/About.aspx"))) // Path to your
{ // HTML file
string fromAddress = "from#yahoo.com";
string toAddress = "to#yahoo.com";
System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage(fromAddress, toAddress);
myMail.Subject = "HTML Message";
myMail.IsBodyHtml = true;
myMail.Body = reader.ReadToEnd(); // Load the content from your file...
//...
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.mail.yahoo.com");
smtp.Credentials = new System.Net.NetworkCredential("from#yahoo.com", "password");
smtp.Send(myMail);
}
But this is giving me this output.
Well you noticed that it is without css. Can I mail an entire asp.net page or do I need to write my code in c# with inline css? Or do I need to create a control with a patern and send it?
You are trying to send unprocessed aspx file. This cannot be successful. You need to process this page (I dont remember what method to use), and dont forget about inline css. So bassicaly you need a new page. And if you need a new page, you can do it with pure html, not in asp.
I made a mail sender in C# but I'm having trouble with the body of the mail. It only sends the texts without pictures, links and other elements. Not to mention, I used RichTextBox for that purpose.
So now my question is: what component to use to send mail with pictures, links and else?
I also enabled IsBodyHtml to true.
What I want to do is to copy the pictures, links and texts (with different colors and size) from Microsoft Word and paste it to control, and when user gets mail he gets the exact same body and layout as I send them.
You'll need to send it as html.
Save your word doc as html and use that.
For the images in your document you can either point to them via their absolute urls (publicly available via the internet).
Or you could use the LinkedResource class.
With the LinkedResource class your images have to specify a cid in the source.
var inlineLogo = new LinkedResource("path/myfile.png");
inlineLogo.ContentId = Guid.NewGuid().ToString();
var imageHtmlFragment = string.Format("<img alt='My Logo' src='cid:{0}' style='width: 250px;height: 60px;'/>",inlineLogo.ContentId);
var newMail = new MailMessage();
var view = AlternateView.CreateAlternateViewFromString(imageHtmlFragment, null, "text/html");
view.LinkedResources.Add(inlineLogo);
newMail.AlternateViews.Add(view);
I want to send a mail with embeded image in ASP.NET
How can i do that?
Regards
Soner
There are generally two ways of doing this, whichever is preferred is up to you.
To literally "embed" the image in the email message itself, you'll want to add it as a Linked Resource and reference the attached resource in the email's HTML.
Alternatively, and more simply, if the image is hosted in a public location then you can just reference that location in the HTML of the email.
Based on the question, it sounds like you are preferring the former approach, but the latter is available as well.
MailAddress sendFrom = new MailAddress(txtFrom.Text);
MailAddress sendTo = new MailAddress(txtTo.Text);
MailMessage myMessage = new MailMessage(sendFrom, sendTo);
MyMessage.Subject = txtSubject.Text;
MyMessage.Body = txtBody.Text;
Attachment attachFile = new Attachment(txtAttachmentPath.Text);
MyMessage.Attachments.Add(attachFile);
SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
emailClient.Send(myMessage);
I believe you can either attach the files and refer them, or alternatively, like in regular HTML, embed them encoded in Base64.
You can go through this link
http://www.dotnetspider.com/resources/41465-Send-Formatted-outlook-email-from-NET-C.aspx
Sample project is also attached.
It shows how to put the link of the image in the application in the html template and send emails.