Can get only Mail Message body? - c#

I use free .net library to read email and I release: If I want to view body message, all free .net email library download body message and attachments. If attachments have a big size, I wait for a long time. Example: I use AE.NET.Mail to read the lastest email:
var dt = DateTime.Now;
Console.WriteLine(dt.ToLongTimeString());
// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
var ic = new ImapClient("imap.gmail.com", "yourEmail", "yourPassword",
ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
var mailCount = ic.GetMessageCount();
ic.SelectMailbox("INBOX");
var message = ic.GetMessage(mailCount - 1);
var body = message.Body;
Console.WriteLine(body);
ic.Disconnect();
ic.Dispose();
Console.WriteLine(DateTime.Now.ToLongTimeString());
Console.WriteLine((DateTime.Now - dt).TotalSeconds);
result: 478,6s with attachment size 23mb.
How can I do if I want to view only body message with fastest speed?

I am giving you link please follow it and try another open source mail library It helps you to consume less time . TRY THIS Then put the code as shown below
MailRepository rep = new MailRepository("imap.gmail.com", 993, true, #"username", "password");
foreach (ActiveUp.Net.Mail.Message email in rep.GetUnreadMails("Inbox"))
{
System.Web.HttpContext.Current.Response.Write(string.Format("<p>{0}: {1}</p><p>{2}</p>", email.From, email.Subject, email.BodyHtml.Text));
}

Related

C# Exchange EmailMessage Send: As soon as I add an attachement, I get error "No mailbox with such guid"

In my application I use some code to send automated mails over our Exchange server.
My current goal is to send a HTML mail with some pictures as a handout. That pictures shall be attachments of the mail.
To this point the code is working (I have changes internal names in the code example):
ExchangeService MailClient = new ExchangeService
{
UseDefaultCredentials = true,
Url = new Uri("https://<domain.of.company>/EWS/Exchange.asmx")
};
EmailMessage msg = new EmailMessage(MailClient);
msg.ToRecipients.Add(new EmailAddress(user.EmailAddress));
msg.Sender = new EmailAddress("sender#domain.of.company");
msg.Subject = "Some text here";
MessageBody Body = new MessageBody
{
BodyType = BodyType.HTML,
Text = NameOfApplication.Properties.Resources.Embedded_HTML_File
};
msg.Body = Body;
msg.SendAndSaveCopy(new FolderId(WellKnownFolderName.SentItems, "sender#domain.of.company")));
With this code the E-Mail get saved in the "Sent" folder and arrives the target mailbox. Success so far.
But as soon I add an attachement by this (no other changes were made)
msg.Attachments.AddFileAttachment(AppContext.BaseDirectory + "Logo.jpg");
SendAndSaveCopy throws an exception with the description "No mailbox with such guid."
When I comment out the AddFileAttachment line the code is working again.
Any idea whats wrong with attachments?
Found the solution. Reading tooltips might help.
Maybe the day will come, when Microsoft will change SendAndSaveCopy to include this step.
But yes: The error message is misleading.

Is there any way to send HTML e-mail with embedded image in UWP

I am working on a uwp app to send html email with embedded image. I was using EASendMail nuget pakage and it was fine after some time my app shows error:
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond. (Exception from
HRESULT: 0x8007274c)
I think the trial period has expired what should I do?
using EASendMailRT;
https://www.emailarchitect.net/easendmail/kb/csharp.aspx?cat=8
I can't find any alternative
try
{
string ToAddress = MailSendPage.toAddressTxtBox;
string Subject = MailSendPage.subjectTxtBox;
SmtpMail oMail = new SmtpMail("TryIt");
oMail.From = new MailAddress(username);
if(!String.IsNullOrEmpty(ToAddress)&& !String.IsNullOrEmpty(Subject))
{
oMail.To.Add(new MailAddress(ToAddress));
oMail.Subject = Subject;
EASendMailRT.SmtpClient oSmtp = new EASendMailRT.SmtpClient();
SmtpServer oServer = new SmtpServer(host);
oServer.User = username;
oServer.Password = password;
oServer.Port = port;
if (IsStackPanalHasImg() == true)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
string[] files = Directory.GetFiles(localFolder.Path + #"\ProjectImages");
foreach (string eachfile in files)
{
foreach (string name in covertToHtml.ControlName)
{
string pattern = string.Format("{0}.jpeg", name);
if (Regex.IsMatch(eachfile, pattern))
{
Attachment oAttachment = await oMail.AddAttachmentAsync(eachfile);
oAttachment.ContentID = name;
}
}
}
}
await oSmtp.SendMailAsync(oServer, oMail);
popUpMsgs.popup(" The Mail has been sent");
}
}
catch (Exception ep)
{
popUpMsgs.popup(String.Format("Failed to send email with the following error: {0}", ep.Message));
}
The built-in e-mail API only support sending plain text e-mail messages as Docs state:
This method only sends plain text messages. You can't set the body of the message to the HTML format.
What you can do is attach images to the e-mail:
EmailMessage mail = new EmailMessage();
mail.Sender = new EmailRecipient("test#example.com");
mail.To.Add(new EmailRecipient("someone#example.com"));
mail.Subject = "Hello";
mail.Body = "World";
var file = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Assets/StoreLogo.png"));
mail.Attachments.Add(new EmailAttachment(file.Name, file));
await Windows.ApplicationModel.Email.EmailManager.ShowComposeNewEmailAsync(mail);
In addition, sending attachments works well only in case of the built-in UWP Outlook Mail client. Classic Outlook will most likely ignore the attachments altogether.
If you need to embed the image, you will need to use a e-mail service. I can recommend SendGrid or MailGun. Both have C# APIs which work like a breeze. They are also free for limited number of e-mails.
There are several ways you can embed the images in a HTML e-mail message.
The oldest is using CID (Content ID) which you were using in your question.
Second option is using Base64 encoding. You first turn your image into a Base64 string. There are many tutorials on this, for example in this blogpost. Then you can just embed the image in the src of your <img> tag:
<img src="data:image/jpeg;base64, YOURIMAGEINBASE64"/>
Finally you can embed an image which is hosted somewhere. This scales the best if you need to send the e-mail to many recipients, but of course requires actually hosting the image somewhere. Of the three methods it is also supported in most clients.
All three approaches are described in detail in this post.

Sparkpost C# API add attachments to templates

I've been going thumbing through the documentation and searching the internet to find documenation on how to add attachments to created templates. I'm using darrencauthon's CSharp-Sparkpost to handle the API calls. So far what I have is not working. Does anyone have a working solution (possible?) or a better solution for C#? I'm not opposed to using a different library. This is the link to CSharp-Sparkpost
Here's what I've got so far:
var t = new Transmission();
t.Content.From.Email = "from#thisperson.com";
t.Content.TemplateId = "my-template-email";
new Recipient
{
Address = new Address { Email = recipient }
}
.Apply(t.Recipients.Add);
new Attachment
{
Data = //CSVDATA,
Name = "Table.csv",
Type = "text/csv"
}.Apply(t.Content.Attachments.Add);
var client = new SparkPost.Client(Util.GetPassword("sparkpostapikey"));
client.Transmissions.Send(t).Wait();
I've verified that I can send this attachment without a template and also verified that I can send this template without the attachment. So... the Email is getting sent; however, the content received is only the template and substitution data. No attachment with the template email.
Using Darren's library, and combining the requirements for my project, this is the solution I've come up with. I'm just making an additional API call to grab the template Html so I can build the transmission without having to send the template_id. Still using the CSharp-Sparkpost library to make all of the calls. I modified Darren's example SendInline program as such:
static async Task ExecuteEmailer()
{
var settings = ConfigurationManager.AppSettings;
var fromAddr = settings["fromaddr"];
var toAddr = settings["toaddr"];
var trans = new Transmission();
var to = new Recipient
{
Address = new Address
{
Email = toAddr
},
SubstitutionData = new Dictionary<string, object>
{
{"firstName", "Stranger"}
}
};
trans.Recipients.Add(to);
trans.SubstitutionData["firstName"] = "Sir or Madam";
trans.Content.From.Email = fromAddr;
trans.Content.Subject = "SparkPost sending attachment using template";
trans.Content.Text = "Greetings {{firstName or 'recipient'}}\nHello from C# land.";
//Add attachments to transmission object
trans.Content.Attachments.Add(new Attachment()
{
Data = Convert.ToBase64String(System.IO.File.ReadAllBytes(#"C:\PathToFile\ExcelFile.xlsx")),
Name = "ExcelFile.xlsx",
Type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
Console.Write("Sending mail...");
var client = new Client(settings["apikey"]);
client.CustomSettings.SendingMode = SendingModes.Sync;
//retrieve template html and set Content.Html
var templateResponse = await client.Templates.Retrieve("template-email-test");
trans.Content.Html = templateResponse.TemplateContent.Html;
//Send transmission
var response = client.Transmissions.Send(trans);
Console.WriteLine("done");
}
Oh actually, I see now -- you are talking about adding attachments to templates, not attachments.
My answer to that is that back when I developed this library, attachment on templates was not supported by SparkPost itself.
My library allows you to try it, but that's because every template and non-template emails are considered "transmissions." So if you create a transmission, it has the option of adding attachments... but if you send the transmission with a template id, the attachment is ignored.
I could throw an error, or somehow design the API around this limitation, but what if they stopped ignoring the attachment but my library threw an error? I designed the library for flexibility as the SparkPost web API grew, and I didn't want my library to get in the way.
If you want to test if you're sending the attachment right, send your transmission without a transmission id, and instead with a subject and email body. If the email goes through and you get an attachment, then you know it's because of this template/attachment restriction from SparkPost.
NOTE: I'm putting this answer on Stack Overflow, and it's possible that this dated message will no longer be valid in the future.
I'm Darren Cauthon, the primary author of this library.
I have attachment support in my acceptance tests, which are run before each release. The link is below, but the code should be as simple as:
// C#
var attachment = File.Create<Attachment>("testtextfile.txt");
transmission.Content.Attachments.Add(attachment);
https://github.com/darrencauthon/csharp-sparkpost/blob/3a8cb1efbb8c9a0448c71c126ce7f88759867fb0/src/SparkPost.Acceptance/TransmissionSteps.cs#L56

How to read latest email conversation HTML body from specific email using Microsoft Exchange webservice

I am using EWS to read email body part alone from email of inbox.
I need to extract only replied email body instead of whole email body.
e.g.
************
A This is good tenant.
Regards,
Test
From:test#gmail.com
To: ----
----------
----------
Hi User, Data has been populated. Please reply with A or R with comments.
Regard
Admin.
************
So when I read email body of above email I get the whole body mentioned above. But what I need is only:
************
A This is good tenant.
Regards,
Test
************
which is having latest replied email body only.
This approach with UniqueBody works for me:
// ensure that username, password, domain and smtpAddress are set
var service = new ExchangeService {
PreAuthenticate = true,
Credentials = new WebCredentials(username, password, domain),
};
service.AutodiscoverUrl(smtpAddress, redirect => true);
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, smtpAddress);
var inbox = Folder.Bind(service, new FolderId(WellKnownFolderName.Inbox));
var fir = inbox.FindItems(new ItemView(10));
foreach (var ir in fir) {
var msg = EmailMessage.Bind(service, ir.Id, new PropertySet(EmailMessageSchema.UniqueBody));
Console.WriteLine(msg.UniqueBody.Text);
}
For any follow-up message in the results, the msg.UniqueBody.Text property contains only the parts that are new in that message.
Note that there might be better ways to do this, but this works in my quick test (against Exchange Online).

MailChimp (Mandrill) for .NET why email includes Image?

I'm using MailChimp for .NET from this nuget https://www.nuget.org/packages/mcapi.net/1.3.1.3 and tried sending emails. But the email I received include image (unseen image) even if I'm just sending simple html. Has anyone encountered it? How to get rid of this unseen image? Please help.
Below is my sample email message.
var api = new MandrillApi("XXXXXXXXXXX");
var recipients = new List<Mandrill.Messages.Recipient>();
var name = string.Format("{0} {1}", "Jobert", "Enamno");
recipients.Add(new Mandrill.Messages.Recipient("recipient#gmail.com", name));
var message = new Mandrill.Messages.Message()
{
To = recipients.ToArray(),
FromEmail = "admin#mysite.com",
Subject = "Test Email",
Html = "<div>Test</div>"
};
MVList<Mandrill.Messages.SendResult> result;
result = api.Send(message);
Received Email
When clicked No image shown
You're seeing this because Mandrill uses a small invisible graphic for open tracking. You'd want to either disable open tracking in the API call you're making or on the Sending Options page in your Mandrill account.

Categories

Resources