I'm trying to pull all my contacts out of Outlook.
I have tried many things but nothing works for me,
I would love to hear from your experience what is the trivial way to do this.
This is one way I tried to do:
Using SPIRE.EMAIL
// Create an imapclient with host, user and password
ImapClient client = new ImapClient();
client.Host = "outlook.office365.com";
client.Username = "#Your email address";
client.Password = "#Your email password";
client.ConnectionProtocols = ConnectionProtocols.Ssl;
client.Port = 143;
client.Connect();
client.Select("Inbox");
// Get a collection of messages
var addressSet = new HashSet<string>();
ImapMessageCollection msg = client.GetAllMessageHeaders();
for (int i = 0; i < msg.Count; i++)
{
string address = msg[i].From.Address;
addressSet.Add(address);
}
Related
I have a simple table(MyEmail) in SQL with some emails that need to be sent, for example:
ID Email
1 name#yahoo.com
2 something2#yahoo.com
3 name3#google.com
4 something4#yahoo.com
I made a stored procedure(GetAddress) to collect them so I can later store them into a variable:
SELECT Email
FROM dbo.MyEmai
I need help with the C# part of the code:
var MyEmails = new List<Email>();
SqlCommand cmdEmails = new SqlCommand("GetAddress", connection);
SqlDataReader rdEmails = cmdEmails.ExecuteReader();
while (rdEmails.Read())
{
MyEmails.Add(new Email() { MyEmails = rdEmails[0].ToString() }); // as an example
}
This code returns list but emails are located bellow WebApplication.MyPage.
Email names.
MyEmails return :
WebApplication.MyPage.Email > name#yahoo.com
WebApplication.MyPage.Email > something2#yahoo.com ...
And I need this WebApplication.MyPage.Email removed so only emails will be shown as strings first.
Code that sends emails:
SmtpClient client = new SmtpClient();
client.Port = 112;
client.Host = "my-smtp";
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("myEmail#provider.com", "");
MailMessage mm = new MailMessage(LocalName, LocalName + MyEmails, "New Mail subject", "This is Email body !");
client.Send(mm);
So because of this MyEmails has an error : Error 24 Argument 2: cannot convert from 'System.Collections.Generic.List' to 'string'
Can someone help me with this?
Thanks in advance!
The MailMessage class from .Net does not accepts a List as a valid parameter. Iiterate over your collection creating multiple mailmessage.
The code should look something like this
foreach (var emailadressObject in myEmails)
{
// get your emailadres string from your object..
// Bit confusion using a collection MyEmails and a Property in you mail objetc with MyEmails
var emailadresstring = emailadressObject.MyEmails;
var message = new MailMessage("from#me.com", emailadresstring, "New Mail subject", "This is Email body !");
// Do you magic with the mail message
}
I want to create a table for these strings and send it via email the problem is that these string are array which may have multiple values and i can't use loop inside string.
So Please help me how to solve it
Thanks in Advance
string CusID = Request["CusID"];
string[] Name = Request["Name"].Split(char.Parse(","));
string[] Code = Request["Code"].Split(char.Parse(","));
string SellDate = Request["SellDate"];
string[] SellQuantity = Request["SellQuantity"].Split(char.Parse(","));
string[] SellPrice = Request["SellPrice"].Split(char.Parse(","));
string[] Paid = Request["Paid"].Split(char.Parse(","));
string[] Status = Request["Status"].Split(char.Parse(","));
string[] Discount = Request["Discount"].Split(char.Parse(","));
for (int i = 0; i < Name.Length; i++)
{
var totalprice = Convert.ToInt32(SellQuantity[i]) * (Convert.ToInt32(SellPrice[i]) - Convert.ToInt32(Discount[i]));
var insert = db.Database.ExecuteSqlCommand(#"insert into Details(CusID,Name,Code,SellDate,SellQuantity,SellPrice,Paid,[Status],Discount)
Values({0},{1},{2},{3},{4},{5},{6},{8},{9})", CusID, Name[i], Code[i], SellDate, SellQuantity[i], SellPrice[i], Paid[i], totalprice, Status[i],Discount[i]);
}
try
{
MailMessage mail = new MailMessage();
mail.To.Add("aspmvcmail#gmail.com");
mail.From = new MailAddress("abcdefghijklm#gmail.com");
mail.Subject = "hi "+DateTime.Now;
string Body = // store table in this string
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //SMTP Server Address of gmail
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("abcdefghijklm#gmail.com", "**********");
// Smtp Email ID and Password For authentication
smtp.EnableSsl = true;
smtp.Send(mail);
return Json("Your Message Send Successfully.", JsonRequestBehavior.AllowGet);
}
catch
{
return Json("Error............", JsonRequestBehavior.AllowGet);
}
I want to read email from my yahoo mail account. I am using "OpenPop.Pop3" to read email from my yahoo mail account, I am using below code :-
using OpenPop.Pop3;
public DataTable ReadEmailsFromId()
{
DataTable table = new DataTable();
try
{
using (Pop3Client client = new Pop3Client())
{
client.Connect("pop.mail.yahoo.com", 995, true); //For SSL
client.Authenticate("Username", "Password", AuthenticationMethod.UsernameAndPassword);
int messageCount = client.GetMessageCount();
for (int i = messageCount; i > 0; i--)
{
table.Rows.Add(client.GetMessage(i).Headers.Subject, client.GetMessage(i).Headers.DateSent);
string msdId = client.GetMessage(i).Headers.MessageId;
OpenPop.Mime.Message msg = client.GetMessage(i);
OpenPop.Mime.MessagePart plainTextPart = msg.FindFirstPlainTextVersion();
string message = plainTextPart.GetBodyAsText();
}
}
}
return table;
}
Same code is able to access other mails emails like gmail,outlook but while working with yahoo mail emails i am able to get Subject, Date but when came to message part that is:
OpenPop.Mime.Message msg = client.GetMessage(i);
OpenPop.Mime.MessagePart plainTextPart = msg.FindFirstPlainTextVersion();
Its give error "The stream used to retrieve responses from was closed".
Here is the "StackTrace":
at OpenPop.Pop3.Pop3Client.IsOkResponse(String response)
at OpenPop.Pop3.Pop3Client.SendCommand(String command)
at OpenPop.Pop3.Pop3Client.Disconnect()
at OpenPop.Pop3.Pop3Client.Dispose(Boolean disposing)
at OpenPop.Pop3.Disposable.Dispose()
Please let me know if i missing something or doing something wrong.
Also I have make yahoo mail emails to be accessed anywhere using POP.
First, based on your code snippet, you are downloading each message 4 times. That's going to be super slow.
As far as why you are getting the error, I do not know. I do not get an error using MailKit:
using MimeKit;
using MailKit;
using MailKit.Net.Pop3;
public DataTable ReadEmailsFromId()
{
DataTable table = new DataTable();
try
{
using (Pop3Client client = new Pop3Client())
{
client.Connect("pop.mail.yahoo.com", 995, true); //For SSL
client.Authenticate("Username", "Password");
for (int i = client.Count - 1; i >= 0; i--)
{
var msg = client.GetMessage (i);
table.Rows.Add(msg.Subject, msg.Date);
string msdId = msg.MessageId;
string message = msg.TextBody;
}
}
}
return table;
}
I have following code for sending an email alert to around 60 users when an extract gets uploaded. However something strange is happening, it is sending to the previous query results not the new ones. The only difference is the quantity of users before it was sending to only a few people now its sending to a larger quantity. But on the code with larger quantity the application seems to not see that it has changed and sends to previous users. Like its cached the query or something. I don't know whats going on. But when I do change it to just one email address it works fine and picks up changes.
if (Session["ExtractNo"].ToString() == "Extract 1")
{
//Connection String (SendEmail)
string SendEmail = ConfigurationManager.ConnectionStrings["SendEmail"].ConnectionString;
SqlDataReader reader;
String SendMessage = "SELECT Name, Position, Email FROM AuthorisedStaff Where Position = 'CM' or Position = 'DHOD' or Position = 'HOD'"; //<---- change position before launch
using (SqlConnection myConnection = new SqlConnection(SendEmail))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(SendMessage, myConnection);
ArrayList emailArray = new ArrayList();
reader = myCommand.ExecuteReader();
var emails = new List<EmailCode>();
while (reader.Read())
{
emails.Add(new EmailCode
{
Email = Convert.ToString(reader["Email"]),
Name = Convert.ToString(reader["Name"]),
Position = Convert.ToString(reader["Position"])
});
}
foreach (EmailCode email in emails)
{
//Email Config
const string username = "roll#test.co.uk"; //account address
const string password = "######"; //account password
SmtpClient smtpclient = new SmtpClient();
MailMessage mail = new MailMessage();
MailAddress fromaddress = new MailAddress("roll#test.co.uk", "PTLP"); //address and from name
smtpclient.Host = "omavex11"; //host name for particular email address
smtpclient.Port = 25; //port number for particular email address
mail.From = fromaddress;
mail.To.Add(email.Email);
mail.Subject = ("PTLP Check");
mail.IsBodyHtml = true;
//change context of message below as appropriate
mail.Body = HttpUtility.HtmlEncode(email.Name) + " <br /> <p>Part Time Lecturer Payroll details are now available for checking. If any changes need made please notify MIS as soon as possible. </p> <p>Please ensure all Adjustments have also been submitted. All Adjustments not submitted on time will be paid the following month. </p> ";
//smtpclient.EnableSsl = true;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
smtpclient.Send(mail);
}
}
}
Try clearing the list first before adding new items/objects
I assume that this
var emails = new List<EmailCode>();
is the list.
I intended to get all my messages in the Inbox folder and put them into the datagridview component.But the sentence "var message = client.Inbox.GetMessage(uids.Count - i - 1);" throws an exception:The IMAP server did not return the requested message. Is there anything wrong with my code?
//get a imapclient and connect to the server
string loginemail = UserInfo.LoginEmail;
string password = UserInfo.LoginPassword;
var client = new ImapClient();
client.Connect("imap.qq.com", 993, SecureSocketOptions.SslOnConnect);
client.Authenticate(loginemail, password);
client.Inbox.Open(FolderAccess.ReadOnly);
var uids = client.Inbox.Search(SearchQuery.All);
//get all the messages from the specified folder
for (int i = 0; i < uids.Count; i++)
{
dataGridView1.Rows.Add(1);
var message = client.Inbox.GetMessage(uids.Count - i - 1);
dataGridView1.Rows[i].Cells[0].Value = message.From.ToString();
if (message.Subject != null) { dataGridView1.Rows[i].Cells[1].Value = message.Subject.ToString(); }
else { dataGridView1.Rows[i].Cells[1].Value = ""; }
dataGridView1.Rows[i].Cells[2].Value = message.Date.ToString();
}
The only way to figure out the problem is to follow the directions in the MailKit FAQ to get a protocol log and look to see what the server is sending as a reply.