how to send email to multiple email addresses - c#

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

Related

How to Add CC or Bcc in Send Email With SendGrid in .NET Core 3.1 and C#

How do I send an email With CC And BCC?
I am using .NET Core 3.1 and wrote this Send method:
public async Task<Response> Send(string ToUser, string Subject, string TextContent, string HtmlContent, string base64context = null, string filename = "")
{
string apiKey = AppConfiguration.SendGridApiKey;
SendGridClient client = new SendGridClient(apiKey);
EmailAddress from = new EmailAddress(AppConfiguration.SendGridFromEmail, AppConfiguration.SendGridFromName);
EmailAddress toMail = new EmailAddress(ToUser);
SendGridMessage msg = MailHelper.CreateSingleEmail(from, toMail, Subject, TextContent, HtmlContent);
if(!string.IsNullOrWhiteSpace(base64context) && !string.IsNullOrWhiteSpace(filename))
{
msg.AddAttachment(filename, base64context);
}
return await client.SendEmailAsync(msg);
}
As per SendGrid's documentation and source code, here's how:
SendGridMessage msg = new SendGridMessage();
msg.AddCc(new EmailAddress("test1#example.com", "Example User1"));
msg.AddBcc(new EmailAddress("test2#example.com", "Example User2"));

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

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.

Using System.Net.Mail to send email from Database list of user

I have the following email function that sends an email to a list of users. I add the users with the method message.To.Add(new MailAddress("UserList#email.com")):
Using System.Net.Mail
protected void SendMail()
{
//Mail notification
MailMessage message = new MailMessage();
message.To.Add(new MailAddress("UserList#email.com"));
message.Subject = "Email Subject ";
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(message);
}
But, how can I connect to a SQL-Server Db and get the list of users from a table, instead of from this function? Thanks for the help!
I figured it out myself in the most simple way. I hope this help someone else. Thanks to everybody who responded with positive comments, have the ability to think, and use common sense.
Using System.Net.Mail
protected void SendMail()
{
//Mail notification
MailMessage message = new MailMessage();
message.Subject = "Email Subject ";
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
SqlCommand cmd = null;
string connectionString = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
string queryString = #"SELECT EMAIL_ADDRESS FROM EMAIL WHERE EMAIL_ADDRESS = EMAIL_ADDRESS";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
cmd = new SqlCommand(queryString);
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
var to = new MailAddress(reader["EMAIL_ADDRESS"].ToString());
message.To.Add(to);
}
// Passing values to smtp object
smtp.Send(message);
// Call Close when done reading.
reader.Close();
}
}
You could create this utilities.cs file in your current project and paste in the following code and see how much easier it is to read
public class utilities
{
public static string ConnectionString
{
get { return ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString; } //change dbconn to whatever your key is in the config file
}
public static string EmailRecips
{
get
{
return ConfigurationManager.AppSettings["EmailRecips"];//in the config file it would look like this <add key="EmailRecips" value="personA#SomeEmail.com|PersonB#SomeEmail.com|Person3#SomeEmail.com"/>
}
}
public static string EmailHost //add and entry in the config file for EmailHost
{
get
{
return ConfigurationManager.AppSettings["EmailHost"];
}
}
public static void SendEmail(string subject, string body) //add a third param if you want to pass List<T> of Email Address then use `.Join()` method to join the List<T> with a `emailaddr + | emailAddr` etc.. the Join will append the `|` for you if tell look up how to use List<T>.Join() Method
{
using (var client = new SmtpClient(utilities.EmailHost, 25))
using (var message = new MailMessage()
{
From = new MailAddress(utilities.FromEmail),
Subject = subject,
Body = body
})
{
//client.EnableSsl = true; //uncomment if you really use SSL
//client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
//client.Credentials = new NetworkCredential(fromAddress, fromPassword);
foreach (var address in utilities.EmailRecips.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
message.To.Add(address);
client.Send(message);
}
}
}
//if you want to pass a List and join into a single string of Pipe Delimited string to use in the .Split Function then you can change the method signature to take a string and pass in this to the email for example
var emailList = string.Join("|", YourList<T>);
//then the new email function signature would look like this
public static void SendEmail(string subject, string body, string emailList)
//then you would replace the .Split method with this
foreach (var address in emailList.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
You can do a lot to optimize and generalize the code below - it's as close to your code as possible while doing what you want. It's up to you to figure out how to connect to your database and get the DataReader.Read(). Try -- if you get stuck, ask something specific.
Using System.Net.Mail
protected void SendMail()
{
Dictionary<string,string> recipients = new Dictionary<string,string>
//--select FirstName, Email form MyClients
//while reader.Read(){
recipients.Add(Convert.ToString(reader[0]),Convert.ToString(reader[1]));//adds from user to dictionary
//}
//Mail notification
foreach(KeyValuePair<string,string> kvp in recipients){
MailMessage message = new MailMessage();
message.To.Add(new MailAddress(kvp.Value));
message.Subject = "Hello, "+kvp.Key;
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(message);
}
} //This bracket was outside the code box

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

Categories

Resources