How to get Gmail subjects using Gmail API in C# - c#

I am making an app that can get all the e-mails in Gmail Inbox from a C# console application.
I have this code below that prints out the console the email body contents:
UsersResource.ThreadsResource.ListRequest threadRequest = service.Users.Threads.List("me");
IList<Google.Apis.Gmail.v1.Data.Thread> threads = threadRequest.Execute().Threads;
foreach(var thread in threads)
{
//print gmail body content
Console.WriteLine("{0}", thread.Snippet);
}
So how do I get gmail subjects instead?
Any contribution will be appriciated!

public string GetMail(){
GmailService service = (GmailService)HttpContext.Current.Session["service"];
Message messageFeed = service.Users.Messages.List("me").Execute().Messages.First();
UsersResource.MessagesResource.GetRequest getReq = new UsersResource.MessagesResource.GetRequest(service, "me", messageFeed.Id);
//"raw": Returns the full email message data with body content in the raw field as a base64url encoded string; the payload field is not used.
getReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
Message message = getReq.Execute();
return message.Raw;
}
Getting more data from messages.get in C#
Gmail API
Better solution:
Read the Gmail Inbox Feed with .NET and OAuth

Related

getting "Unknown Mailbox" error when sending email using EWS API (C#)

I'm simply trying to use the Office 365 API to send an email via the "Send()" function, but am getting back Microsoft.Exchange.Webservices.Data.ServiceResponseException: Mailbox does not exist.
Here's my exchange service:
_emailExchangeService =
new ExchangeService(ExchangeVersion.Exchange2013_SP1)
{
Url = new Uri(_settings.ExchangeWebServiceEndpoint),
Credentials = new WebCredentials(_settings.AppEmailUserName, _settings.AppEmailPassword),
TraceEnabled = true,
UseDefaultCredentials = false
};
And here's the code I'm using to send the email:
public void SendEmail(MemoryStream attachment, string body, string subject, string recipients, string fromMailbox)
{
EmailMessage message = new EmailMessage(_emailExchangeService);
message.From = fromMailbox;
message.Subject = subject;
message.Body = new MessageBody(BodyType.Text, body);
message.ToRecipients.Add(recipients);
message.Attachments.AddFileAttachment("FileName", attachment);
message.Send();
}
What mailbox am I forgetting to define when sending this, the sent box? I thought the "from" field would define the mailbox for sending items. I'm just not even sure where to do that and my code looks identical to the docs.
Side note: I know the exchange service is set up correctly because if I define an inbox email address and attempt to FindItems(_inbox) on the mailbox, it works.

Send Reply with attachment using Microsoft Graph API

I've been working with Microsoft graph API to receive and reply to the mail.
I've successfully received and send mails, but as per Graph API docs in reply only a comment can be passed.
https://learn.microsoft.com/en-us/graph/api/message-createreply?view=graph-rest-1.0&tabs=cs
I've developed the send mail code as shown below:-
IList<Recipient> messageToList = new List<Recipient>();
User currentUser = client.Me.Request().GetAsync().Result;
Recipient currentUserRecipient = new Recipient();
EmailAddress currentUserEmailAdress = new EmailAddress();
EmailAddress recepientUserEmailAdress = new EmailAddress();
currentUserEmailAdress.Address = currentUser.UserPrincipalName;
currentUserEmailAdress.Name = currentUser.DisplayName;
messageToList.Add(currentUserRecipient);
try
{
ItemBody messageBody = new ItemBody();
messageBody.Content = "A sample message from Ashish";
messageBody.ContentType = BodyType.Text;
Message newMessage = new Message();
newMessage.Subject = "\nSample Mail From Ashish.";
newMessage.ToRecipients = messageToList;
newMessage.CcRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "abc.xyz#xxxx.com"
}
}
};
newMessage.Body = messageBody;
client.Me.SendMail(newMessage, true).Request().PostAsync();
Console.WriteLine("\nMail sent to {0}", currentUser.DisplayName);
}
catch (Exception)
{
Console.WriteLine("\nUnexpected Error attempting to send an email");
throw;
}
This code is working fine!!
Can someone please share how I can Reply to a mail with attachment and mailbody like I'm able to do in Send mail.
Thanks in advance.
You have to create a reply, add the attachment, and then send the message. With the basic basic /reply endpoint you cant do it.
E.g.:
Create the message draft using POST request
As a response you will get the whole message structure with id set to something like AQMkADAwATMwMAItMTJkYi03YjFjLTAwAi0wMAoARgAAA_hRKmxc6QpJks9QJkO5R50HAP6mz4np5UJHkvaxWZjGproAAAIBDwAAAP6mz4np5UJHkvaxWZjGproAAAAUZT2jAAAA. Lets refer to it as {messageID}.
After that you can create an attachment using POST request to https://graph.microsoft.com/beta/me/messages/{messageID}/attachments
-After step 2 you will see created message in your mailbox Drafts folder. To send it use https://graph.microsoft.com/beta/me/messages/{messageID}/send
Hope it helps.

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.

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.

Can get only Mail Message body?

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));
}

Categories

Resources