Sendgrid- unble to concatinate plaintext along with html hyperlink - c#

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.

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

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

insert a link in to a email send using c#

I develop a program to send emails automatically using c#, and I want to insert a link to a web site to that email. How can I do it?
public bool genarateEmail(String from, String to, String cc, String displayName,
String password, String subjet, String body)
{
bool EmailIsSent = false;
MailMessage m = new MailMessage();
SmtpClient sc = new SmtpClient();
try
{
m.From = new MailAddress(from, displayName);
m.To.Add(new MailAddress(to, displayName));
m.CC.Add(new MailAddress("xxx#gmail.com", "Display name CC"));
m.Subject = subjet;
m.IsBodyHtml = true;
m.Body = body;
sc.Host = "smtp.gmail.com";
sc.Port = 587;
sc.Credentials = new
System.Net.NetworkCredential(from, password);
sc.EnableSsl = true;
sc.Send(m);
EmailIsSent = true;
}
catch (Exception ex)
{
EmailIsSent = false;
}
return EmailIsSent;
}
I want to send a link through this email. How should I add it to email?
You should be able to just add the mark-up for the link in your body variable:
body = "blah blah <a href='http://www.example.com'>blah</a>";
You shouldn't have to do anything special since you're specifying your body contains HTML (m.IsBodyHtml = true).
String body = "Your message : <a href='http://www.example.com'></a>"
m.Body = body;
Within the body. This will require that the body be constructed as HTML so the that a or can be used to render your link. You can use something like StringTemplate to generate the html including your link.
For some dynamic links, the email service providers will not show your link into email body if the link not prepend http (security issues)
like localhost:xxxx/myPage
m.body = "<a href='http://" + Request.Url.Authority + "/myPage'>click here</a>"

Categories

Resources