OpenPop.Net not getting all emails from Gmail - c#

I have this code:
public List<Attachment> GetAttachments() {
string hostname = "pop.gmail.com";
int port = 995;
bool useSSL = true;
string attachmentType = "application/pdf";
string email = "myemail#gmail.com";
string emailFrom = "someone#gmail.com";
string password = TxtBoxPassword.Text;
if (!string.IsNullOrWhiteSpace(password))
{
Pop3Client client = new Pop3Client();
client.Connect(hostname, port, useSSL);
client.Authenticate(email, password, AuthenticationMethod.UsernameAndPassword);
List<Attachment> listAttachments = new List<Attachment>();
int count = client.GetMessageCount();
for (int i = count; i >= 1; i--)
{
Message message = client.GetMessage(i);
if (message.Headers.From.MailAddress.Address == emailFrom)
{
List<MessagePart> attachments = message.FindAllAttachments();
foreach (MessagePart attachment in attachments)
{
if (attachment.ContentType.MediaType == attachmentType)
listAttachments.Add(new Attachment(attachment));
}
}
}
}
}
To read all emails in email account.
It access the email account and get 265 emails from sent/inbox folders.
Currently I have over thousand emails in the account, so I expect to see this number on count of emails.
What is missing in code/Gmail account settings that is preventing me to get all emails?
Thanks

Well, gmail has some quirks when it gets to it's POP3 features. See my answer on What non-standard behaviour features does Gmail exhibit, when it is programmatically used as a POP3 server?. I do not think you can alter any settings that will remedy your problem.

Related

How to set mail message as seen using S22.imap in C#

I used S22.imap package to read all unread emails like below, then I want to mark the unseen mail as seen after reading it, how can I do this please.
string host = "host";
int port = port;
string username = "username";
string password = "psw";
using (ImapClient client = new ImapClient(host, port, username, password, AuthMethod.Login, true))
{
IEnumerable<uint> uids = client.Search(SearchCondition.Unseen());
// Download mail messages from the default mailbox.
IEnumerable<MailMessage> messages = client.GetMessages(uids, FetchOptions.Normal);
foreach (var item in messages)
{
string from = item.From.ToString();
string body = item.Body.ToString();
string subject = item.Subject.ToString();
Console.WriteLine(from + "-" + body + "-" + subject);
}
}
Try:
MessageFlag[] flags = new[] { MessageFlag.Seen };
client.SetMessageFlags(id, null, flags);

how to send email to multiple email addresses

I am having a problem sending email to multiple email addresses using C#.
var email = new EmailMessageApiDto
{
SendTo = input.SendTo,
Body = input.Body,
MailVariables = new List<VariableDictionaryDto>(),
Recipient = new EmailRecipientDto
{
EmailAddress = input.SendTo,
FirstName = input.SendTo.Split('#').First(),
LastName = input.SendTo.Split('#').Last()
},
SendDateTime = Clock.Now,
Subject = input.Subject,
Sender = new EmailSenderDto
{
EmailAddress = account.SmtpSettings.DefaultSenderAddress,
FirstName = account.SmtpSettings.DefaultSenderDisplayName.Split(' ').First(),
LastName = account.SmtpSettings.DefaultSenderDisplayName.Split(' ').Last()
},ReplyTo = account.SmtpSettings.DefaultSenderAddress
};
Do I need to do some escape for the ";" delimiter: If so, how?
I am not familiar with the classes you are using, but you can send an e-mail to multiple users using the .Net Framework
using System.Net.Mail;
public static void SendMessage(string[] sendTo, string sendFrom, string subject, string messageText, string cc, string attachmentPath)
{
// Create a new message copying the person who sent it
using (var message = new MailMessage(sendFrom, sendFrom, subject, messageText))
{
// Add each email address to send to.
foreach (string s in sendTo)
message.To.Add(new MailAddress(s));
// Add cc to the message if not blank.
if (!String.IsNullOrEmpty(cc))
message.CC.Add(new MailAddress(cc));
if (!String.IsNullOrEmpty(attachmentPath))
message.Attachments.Add(new Attachment(attachmentPath));
// Send mail through smtp server.
using (var client = new SmtpClient("yoursmtpserverhere"))
client.Send(message);
}
}

How can I silently send Outlook email?

I've got this code that sends an email with attachment[s]:
internal static bool EmailGeneratedReport(List<string> recipients)
{
bool success = true;
try
{
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
Recipients _recipients = mailItem.Recipients;
foreach (string recip in recipients)
{
Recipient outlookRecipient = _recipients.Add(recip);
outlookRecipient.Type = (int)OlMailRecipientType.olTo;
outlookRecipient.Resolve();
}
mailItem.Subject = String.Format("Platypus Reports generated {0}", GetYYYYMMDDHHMM());
List<String> htmlBody = new List<string>
{
"<html><body><img src=\"http://www.platypus.com/wp-content/themes/duckbill/images/pa_logo_notag.png\" alt=\"Pro*Act logo\" ><p>Your Platypus reports are attached.</p>"
};
htmlBody.Add("</body></html>");
mailItem.HTMLBody = string.Join(Environment.NewLine, htmlBody.ToArray());
. . . // un-Outlook-specific code elided for brevity
FileInfo[] rptsToEmail = GetLastReportsGenerated(uniqueFolder);
foreach (var file in rptsToEmail)
{
String fullFilename = Path.Combine(uniqueFolder, file.Name);
if (!File.Exists(fullFilename)) continue;
if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
{
mailItem.Attachments.Add(fullFilename);
}
MarkFileAsSent(fullFilename);
}
mailItem.Importance = OlImportance.olImportanceHigh;
mailItem.Display(false);
}
catch (System.Exception ex)
{
String exDetail = String.Format(ExceptionFormatString, ex.Message,
Environment.NewLine, ex.Source, ex.StackTrace, ex.InnerException);
MessageBox.Show(exDetail);
success = false;
}
return success;
}
However, it pops up the email window when ready, which the user must respond to by either sending or canceling. As this is in an app that sends email based on a timer generating reports to be sent, I can't rely on a human being present to hit the "Send" button.
Can Outlook email be sent "silently"? If so, how?
I can send email silently with gmail:
private void EmailMessage(string msg)
{
string FROM_EMAIL = "sharedhearts#gmail.com";
string TO_EMAIL = "cshannon#platypus.com";
string FROM_EMAIL_NAME = "B. Clay Shannon";
string TO_EMAIL_NAME = "Clay Shannon";
string GMAIL_PASSWORD = "theRainNSpainFallsMainlyOnDonQuixotesHelmet";
var fromAddress = new MailAddress(FROM_EMAIL, FROM_EMAIL_NAME);
var toAddress = new MailAddress(TO_EMAIL, TO_EMAIL_NAME);
string fromPassword = GMAIL_PASSWORD;
string subject = string.Format("Log msg from ReportScheduler app sent
{0}", DateTime.Now.ToLongDateString());
string body = msg;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
...but when I do that, I have to supply my gmail password, and I don't really want to do that (expose my password in the source code).
So, how can I gain the benefits of gmailing (silence) and Outlook (keeping my password private)?
If you want the shortest way:
System.Web.Mail.SmtpMail.SmtpServer="SMTP Host Address";
System.Web.Mail.SmtpMail.Send("from","To","Subject","MessageText");
This was code that I was reusing from another project where I wanted the send dialog to display, and for the email only to be sent when the user hit the "Send" button. For that reason, it didn't call "send"
To get the email to send silently/unattended, I just needed to add a call to "mailItem.Send()" like so:
mailItem.Importance = OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Send(); // This was missing

how to protect classify sent emails as spam in asp.net [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I lower the spam score of my email message?
I have this c# code that can send lots of emails to people . but emails that I sent has classified as spam .what should I do .is there any change that I should apply to my code?I try to get email addresses from sql server data base .and My code can attach one file .
Entities context = new Entities();
var query = from c in context.Emails select c.EmailAddress;
MailMessage mail = new MailMessage();
Regex sample = new Regex(#"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*
#[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
int total = 0;//number of all emails
int count = 0;//counter for putting interrupt between each 10 sending
int failed = 0;//number of failed sending
int success = 0;//number of successful sending
double totalsize = 0;//size of attachment file
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
foreach (Attachment attachment in mail.Attachments)
{
string size =attachment.ContentStream.Length.ToString ();
totalsize=Convert .ToDouble (size);
}
}
foreach (var c in query)
{
if (count == 10)
{
Thread.Sleep(10000);
count = 0;
}
mail.From = new MailAddress("hadi#myhost.com");
mail.Bcc.Add(new MailAddress(c.ToString()));
mail.Subject = "hello";
mail.IsBodyHtml = true;
mail.Body = FCKeditor1.Value.ToString();
SmtpClient smtp = new SmtpClient();
smtp.Host = "localhost";
smtp.Port = 25;
if ((sample.IsMatch(c.ToString())) && (sample .IsMatch (mail .From .ToString ())) && (totalsize<1000000))
{
try
{
smtp.Send(mail);
//Response.Write("email has sent to " + c.ToString());
success++;
}
catch
{
//Response.Write("email has not sent to " + c.ToString());
failed++;
}
count++;
}
total++;
}
You don't have to do anything with your code to make it not spam. All you have to do is to make sure you are sending email from a host that should not have "Open Relay" means not everybody can send email from it.
Send your email from proper server and with proper email signature , so that when receiver checks back for authentication they should authenticate your email source server and signature validated from your email host.

C# Send bulk email

I am wondering what the best way to send bulk emails is using System.Net.Mail and C#.
Is it a good idea to send emails in batches?
Should I use the to field or BCC?
I prefer using the To field and send e-mails one at a time in stead of using the BCC field. This way the receiver sees his e-mail address in the TO field (less spam-sensitive) and you can personalize the e-mails per user in the future.
For the sending, you should use batches to prevent timeouts and heavy server loads. You could use a queue for all the e-mails and send them using a configurable schedule using a service, scheduled task, or whatever.
If you do send a single email to multiple recipient and if it's for sending emails to people who don't know each other you should definitely use the BCC field otherwise you're sure to make a lot of people quite angry when you're giving away their email addresses to strangers (and you might also be breaking some kind of data protection law depending on where you live).
bulk Emails using mailkit you have to import it by nuget manager
set in gmail https://myaccount.google.com/lesssecureapps?pli=1 to be on
public void ReadFileAndSend()
{
using (StreamReader reader = new StreamReader(#"d:\Email.txt"))
{
while (!(reader.ReadLine() == null))
{
String line = reader.ReadLine();
if (line != "")
{
try
{
Send("", line.Trim());
Thread.Sleep(500);
}
catch
{
}
}
}
Console.ReadLine();
}
}
public void Send(String FromAddress,String ToAddress)
{
try
{
string FromAdressTitle = "";
string ToAdressTitle = "";
string Subject = "";
string BodyContent = "";
string SmtpServer = "smtp.gmail.com";
int SmtpPortNumber = 587;
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
mimeMessage.Subject = Subject;
mimeMessage.Body = new TextPart("html")
{
Text = BodyContent
};
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect(SmtpServer, SmtpPortNumber, false);
client.Authenticate("your email", "pass");
client.Send(mimeMessage);
Console.WriteLine("The mail has been sent successfully !!");
client.Disconnect(true);
}
}
catch (Exception ex)
{
throw ex;
}
}

Categories

Resources