How to get the recipients from email - c#

I'm using Outlook.Interop in order to to get the Html Body from email recieved.
I'm trying to get the recipients' email address, but only getting a name of the recipients and not the full email address.
Application myApp = new ApplicationClass();
NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderInbox).Folders["digitel"];
List<MailItem> ReceivedEmails = new List<MailItem>();
foreach (MailItem mail in myInbox.Items)
{ ReceivedEmails.Add(mail); }
var Recipients = ReceivedEmails[0].Recipients.ToString();

Checkout the following snippet:
foreach (Outlook.Recipient recip in ReceivedEmails[0].Recipients)
{
Debug.WriteLine(recip.AddressEntry.GetExchangeUser().PrimarySmtpAddress.ToSt‌​‌​ring());
}
Let me know if you have any problem :)!

Related

Send Mail with Outlook on Exchange Account

I want to send EMails with C# and the Microsoft.Office.Interop.Outlook library.
I am locked in, on my Outlook account with a#domain.com and got the rights on the exchange server to send mails from b#domain.com and c#domain.com.
I don't find any way to send a mail with B or C.
I got everything working for my user account which has the mail a#domain.com.
Now I can't find a way to get the account of b#domain.com and send a mail in the name of B.
My Question:
How do I get access to the other accounts?
That's the code I have:
using Outlook = Microsoft.Office.Interop.Outlook;
public static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress)
{
// Loop over the Accounts collection of the current Outlook session.
Outlook.Accounts accounts = application.Session.Accounts;
if (_IsDebug)
Console.WriteLine($"Anzahl Accounts: {accounts.Count}");
foreach (Outlook.Account account in accounts)
{
// When the e-mail address matches, return the account.
if (_IsDebug)
Console.WriteLine($"Account: {account.SmtpAddress}");
if (String.Compare(account.SmtpAddress, smtpAddress, true) == 0)
{
return account;
}
}
throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", smtpAddress));
}
static void SendEMail(string emailadress)
{
try
{
var outlookApplication = new Outlook.Application();
var outlookMailItem = (Outlook.MailItem)outlookApplication.CreateItem(Outlook.OlItemType.olMailItem);
outlookMailItem.SendUsingAccount = GetAccountForEmailAddress(outlookApplication, ConfigurationManager.AppSettings[SENDER]);
if (_IsDebug)
Console.WriteLine($"Absender: {outlookMailItem?.SendUsingAccount?.SmtpAddress}");
outlookMailItem.HTMLBody = ConfigurationManager.AppSettings[BODY];
if (_IsDebug)
Console.WriteLine($"Body: {outlookMailItem?.HTMLBody}");
var file = GetPDFFile();
if (_IsDebug)
Console.WriteLine($"File: {file?.Name}");
if (file == null)
{
Console.WriteLine("Keine Datei gefunden!");
return;
}
string attachementDisplayName = file.Name;
int attachementPosition = outlookMailItem.HTMLBody.Length + 1;
int attachementType = (int)Outlook.OlAttachmentType.olByValue;
if (_IsDebug)
Console.WriteLine($"Dateianhang: {file.FullName}");
Outlook.Attachment outlookAttachement = outlookMailItem.Attachments.Add(file.FullName, attachementType, attachementPosition, attachementDisplayName);
outlookMailItem.Subject = ConfigurationManager.AppSettings[SUBJECT];
Outlook.Recipients outlookRecipients = outlookMailItem.Recipients;
Outlook.Recipient outlookRecipient = outlookRecipients.Add(emailadress);
outlookRecipient.Resolve();
outlookMailItem.Send();
outlookRecipient = null;
outlookRecipients = null;
outlookMailItem = null;
outlookApplication = null;
if (_IsDebug)
Console.ReadLine();
}
catch (Exception)
{
throw;
}
}
You have to grant the owner of the sending mailbox Send As permissions on the mailboxes you want to send the emails from. Send on behalf of permissions will work but will say "A on behalf of B" as the sender.

Get destination email addresses from Sent Items folder in Outlook Interop C#

i'm using Outlook Interop and C# to get some mail information to create an excel report. I have email items list from Sent Items folder and i want to get the email address who i sent the mail. I found the "To" property but only return the person name not the address.
Anyone can please help me to return the email addres from Outlook.MailItem object?
You can ask me if you need more information. Thanks!!!!
Here is my code where i am setting the properties:
foreach (object mail in mails)
//mails is a list from Sent Items folder
{
if (mail is Outlook.MailItem)
{
var item = (Outlook.MailItem)mail;
//i need the address in provider email
var providerEmail = someProperty(????);
var name = item.To;
var request= "Other Request";
var emailDate= item.ReceivedTime;
var status = "Closed";
var responseDate= item.CreationTime;
var reportObject = new ReportModel
{
Email = providerEmail ,
Name = name,
Solicitud = request,
EmailDate = emailDate,
Status = status,
ResponseDate = responseDate
};
}
}
MailItem has Recipients property, you can use it to obtain recipient of each type:
To
Cc
Bcc.
Use recipient.Type to recognize recipient type and recipient.Address to obtain its email address.
Example:
protected override void getRecepients(MailItem OLitem, StringBuilder toStringBuilder,
StringBuilder ccStringBuilder, StringBuilder bccStringBuilder)
{
try
{
var recipients = OLitem.Recipients;
string parent = string.Empty;
foreach (Microsoft.Office.Interop.Outlook.Recipient recipient in recipients)
{
switch (recipient.Type)
{
case (int)Microsoft.Office.Interop.Outlook.OlMailRecipientType.olTo:
toStringBuilder.Append(recipient.Address + ", ");
if (parent == string.Empty)
{
parent = recipient.Address;
}
break;
case (int)Microsoft.Office.Interop.Outlook.OlMailRecipientType.olCC:
ccStringBuilder.Append(recipient.Address + ", ");
break;
case (int)Microsoft.Office.Interop.Outlook.OlMailRecipientType.olBCC:
bccStringBuilder.Append(recipient.Address + ", ");
break;
default:
break;
}
}
}
catch (Exception ex)
{
// do something with error
}
}

MailKit: How to download all attachments locally from a MimeMessage

I have looked at other examples online, but I am unable to figure out how to download and store ALL the attachments from a MimeMessage object.
I did look into the WriteTo(), but I could not get it to work.
Also wondering whether attachments will be saved according to the original file name, and type inside the email.
Here is what I have so far:
using (var client = new ImapClient())
{
client.Connect(Constant.GoogleImapHost, Constant.ImapPort, SecureSocketOptions.SslOnConnect);
client.AuthenticationMechanisms.Remove(Constant.GoogleOAuth);
client.Authenticate(Constant.GoogleUserName, Constant.GenericPassword);
if (client.IsConnected == true)
{
FolderAccess inboxAccess = client.Inbox.Open(FolderAccess.ReadWrite);
IMailFolder inboxFolder = client.GetFolder(Constant.InboxFolder);
IList<UniqueId> uids = client.Inbox.Search(SearchQuery.All);
if (inboxFolder != null & inboxFolder.Unread > 0)
{
foreach (UniqueId msgId in uids)
{
MimeMessage message = inboxFolder.GetMessage(msgId);
foreach (MimeEntity attachment in message.Attachments)
{
//need to save all the attachments locally
}
}
}
}
}
This is all explained in the FAQ in the "How do I save attachments?" section.
Here is a fixed version of the code you posted in your question:
using (var client = new ImapClient ()) {
client.Connect (Constant.GoogleImapHost, Constant.ImapPort, SecureSocketOptions.SslOnConnect);
client.AuthenticationMechanisms.Remove (Constant.GoogleOAuth);
client.Authenticate (Constant.GoogleUserName, Constant.GenericPassword);
client.Inbox.Open (FolderAccess.ReadWrite);
IList<UniqueId> uids = client.Inbox.Search (SearchQuery.All);
foreach (UniqueId uid in uids) {
MimeMessage message = client.Inbox.GetMessage (uid);
foreach (MimeEntity attachment in message.Attachments) {
var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;
using (var stream = File.Create (fileName)) {
if (attachment is MessagePart) {
var rfc822 = (MessagePart) attachment;
rfc822.Message.WriteTo (stream);
} else {
var part = (MimePart) attachment;
part.Content.DecodeTo (stream);
}
}
}
}
}
A few notes:
There's no need to check if client.IsConnected after authenticating. If it wasn't connected, it would have thrown an exception in the Authenticate() method. It would have thrown an exception in the Connect() method as well if it didn't succeed. There is no need to check the IsConnected state if you literally just called Connect() 2 lines up.
Why are you checking inboxFolder.Unread if you don't even use it anywhere? If you just want to download unread messages, change your search to be SearchQuery.NotSeen which will give you only the message UIDs that have not been read.
I removed your IMailFolder inboxFolder = client.GetFolder(Constant.InboxFolder); logic because you don't need it. If you are going to do the SEARCH using client.Inbox, then don't iterate over the results with a different folder object.

How to get the Attachement File

Here I am trying to get all the part of an email separately like body, attachments, address part also So I have the below code . So can I get the attachment files also by using same technique( Using PropertySet class or define RequestedBodyType to something)???
Is there any way to get the contents of Attachment files of any type and I don't need to change the code too much??
// Get the Unread mails from the server
SearchFilter itemFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
// get the emails from Inbox folder
FindItemsResults<Item> emails = service.FindItems(WellKnownFolderName.Inbox, itemFilter, view);
foreach (EmailMessage em in emails)
{
itempropertyset.RequestedBodyType = BodyType.HTML;
em.Load(itempropertyset);
em.IsRead = true;
em.Update(ConflictResolutionMode.AlwaysOverwrite);
EmailProList.HTMLBody = em.Body.Text;
itempropertyset.RequestedBodyType = BodyType.Text;
em.Load(itempropertyset);
EmailProList.Body = em.Body.Text;
itempropertyset.RequestedBodyType =
EmailProList.ToEmailAddr = em.Sender.Address.ToString(); //JG Changed
EmailProList.Subject = em.Subject.ToString();
EmailProList.Type = "Feedback";
}
You can get the attachments like this:
EmailMessage email = item as EmailMessage;
foreach(FileAttachment file in email.FileAttachments)
{
// Process the attachment
}
You can process the attachments by this way.
if (message.HasAttachments && message.Attachments[0] is FileAttachment)
{
FileAttachment fileAttachment = message.Attachments[0] as FileAttachment;
Console.WriteLine("email" + fileAttachment.Name);
fileAttachment.Load(#"D:\\" + fileAttachment.Name);
}

Sending Mails with attachment in C#

I need to send a mail including the exception details (Yellow Screen Of Death) as attachment.
I could get the YSOD as follows:
string YSODmarkup = lastErrorWrapper.GetHtmlErrorMessage();
if (!string.IsNullOrEmpty(YSODmarkup))
{
Attachment YSOD = Attachment.CreateAttachmentFromString(YSODmarkup, "YSOD.htm");
mm.Attachments.Add(YSOD);
}
mm is of type MailMessage, but the mail is not sent.
Here
System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("from", "to", "Exception-Details", htmlEmail.ToString());
is used to bind the body of the mail.
After this only the attachment is added.
While removing the attachment, mail is sent.
Can anyone help me out?
As per the comments from Mr. Albin and Mr. Paul am updating the following
string YSODmarkup = Ex_Details.GetHtmlErrorMessage();
string p = System.IO.Directory.GetCurrentDirectory();
p = p + "\\trial.txt";
StreamWriter sw = new StreamWriter(p);
sw.WriteLine(YSODmarkup);
sw.Close();
Attachment a = new Attachment(p);
if (!string.IsNullOrEmpty(YSODmarkup))
{
Attachment YSOD = Attachment.CreateAttachmentFromString(YSODmarkup, "YSOD.html");
System.Net.Mail.Attachment(server.mappath("C:\\Documents and Settings\\user\\Desktop\\xml.docx"));
MyMailMessage.Attachments.Add(a);
}
Here i attached the contents to a text file and tried the same. So the mail was not sent. Is there any issue with sending mails which contains HTML tags in it. Because i was able to attach a normal text file.
namespace SendAttachmentMail
{
class Program
{
static void Main(string[] args)
{
var myAddress = new MailAddress("jhered#yahoo.com","James Peckham");
MailMessage message = new MailMessage(myAddress, myAddress);
message.Body = "Hello";
message.Attachments.Add(new Attachment(#"Test.txt"));
var client = new YahooMailClient();
client.Send(message);
}
}
public class YahooMailClient : SmtpClient
{
public YahooMailClient()
: base("smtp.mail.yahoo.com", 25)
{
Credentials = new YahooCredentials();
}
}
public class YahooCredentials : ICredentialsByHost
{
public NetworkCredential GetCredential(string host, int port, string authenticationType)
{
return new NetworkCredential("jhered#yahoo.com", "mypwd");
}
}
}

Categories