How to set mail message as seen using S22.imap in C# - 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);

Related

Sendgrid- unble to concatinate plaintext along with html hyperlink

I am using sendgrid to send an email but when I try to concatinate plaintext and html hyperlink it seems to be constructed correct but in email email I get html tag.
my code:
string myHtml = string.Format(#"<a href='{0}'>here</a>", activationLink);
string message = string.Format("Dear {0} {1}\n", FirstName, LastName) + "to verify your email address click ";
SendMail(Email, subject, message, myHtml);
Below is my sendmail method:
public bool SendMail(string To, string Subject, string Message, string htmlContent)
{
try
{
var client = new SendGridClient(ConfigurationManager.AppSettings["Key"].ToString());
EmailAddress from = new EmailAddress(ConfigurationManager.AppSettings["From"].ToString());
var subject = Subject;
EmailAddress to = new EmailAddress(To);
string content = Message;
//var htmlContent = "<strong>Hello, Email!</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, content, htmlContent);
var response = client.SendEmailAsync(msg);
return true;
}
catch (Exception ex)
{
return false;
}
}
This is what I get in email:
here(Clickable)
what I want to appear in mail is:
Dear User to verify your email address click here (Clickable)
Can anyone please help me.

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

send email using system.web.Mail in asp.net without saving attachment on server

When I tried to send Email using system.web.mail I can send the mail successfully without attachment.
But when I tried to send mail using attachment I am getting error : Invalid access (access to the specific directory is denied). Because I am saving the file on server to send mail.
Now My solution for this to send mail using attachment without storing the file on server
Please some one here help me send mail using system.web with attachment without storing the file on server
Below is my previous old code
public void SendMailtoRecruitment()
{
string filePath = FileUpLoad1.PostedFile.FileName;
string filename = System.IO.Path.GetFileName(filePath);
string ext = System.IO.Path.GetExtension(filename);
var path = Server.MapPath("~/App_Data");
StringBuilder sbEmailBody = new StringBuilder();
string strFileName = "";
sbEmailBody.Append("Dear Recruitment Team" + Environment.NewLine + Environment.NewLine);
sbEmailBody.Append("The application is received from the following candidate for the job mentioned in the subject.");
sbEmailBody.Append("\n");
sbEmailBody.Append("Position Id:" + JobId);
sbEmailBody.Append("\n");
sbEmailBody.Append("Position Description:" + jobrole);
sbEmailBody.Append("\n");
sbEmailBody.Append("Candidate First Name :" + First.Text);
sbEmailBody.Append("\n");
sbEmailBody.Append("Candidate Last Name :" + Last.Text);
sbEmailBody.Append("\n");
sbEmailBody.Append("Candidate Email :" + TxtEmailAddress.Text);
sbEmailBody.Append("\n");
sbEmailBody.Append("Candidate Contact No :" + Contact.Text);
sbEmailBody.Append("\n");
sbEmailBody.Append("Reply the Status of the Application as early as posible");
sbEmailBody.Append("\n");
sbEmailBody.Append("\n");
sbEmailBody.Append("\n");
sbEmailBody.Append("\n" + "Sri Tech Consulting" + "\n");
MailMessage mail = new MailMessage();
String fileName = FileUpLoad1.FileName;
if (FileUpLoad1.PostedFile != null)
{
/* Get a reference to PostedFile object */
HttpPostedFile attFile = FileUpLoad1.PostedFile;
/* Get size of the file */
int attachFileLength = attFile.ContentLength;
/* Make sure the size of the file is > 0 */
if (attachFileLength > 0)
{
strFileName = Path.GetFileName(FileUpLoad1.PostedFile.FileName);
// FileUpLoad1.PostedFile.SaveAs(Server.MapPath(strFileName));
MailAttachment attach = new MailAttachment(Server.MapPath(strFileName),MailEncoding.Base64);
mail.Attachments.Add(attach);
}
// mail.Attachments.Add(attach);
// mail.To = "Recruitment#btc-india.in";
mail.To = "rajesh#btc-india.in";
mail.From = "noreply#btc-india.in";
mail.Subject = "Job Application : "+ jobrole;
mail.Body = sbEmailBody.ToString();
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "noreply#btc-india.in"); //set your username here
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "Anuhya#1999"); //set your password here
SmtpMail.SmtpServer = "208.91.198.171";
SmtpMail.Send(mail);
}
}

OpenPop.Net not getting all emails from Gmail

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.

Categories

Resources