Extra new lines in Plain text email via SendGrid - c#

I am using a standard .NET SMTPClient to send a PLAIN text email - as follows:
// Configure mail client
using (SmtpClient mailClient = new SmtpClient(AppConfig.SMTPServer))
{
mailClient.Credentials = new System.Net.NetworkCredential(AppConfig.SMTPUsername, AppConfig.SMTPPassword);
// Create the mail message
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(AppConfig.SMTPSenderEmail, AppConfig.SMTPSenderDisplay);
foreach (string recipient in recipients)
{
mailMessage.To.Add(new MailAddress(recipient));
}
mailMessage.Bcc.Add(new MailAddress(AppConfig.SMTPBC));
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = false;
// Attachments
if (attachments != null && attachments.Any())
{
foreach (KeyValuePair<string, Byte[]> attachment in attachments)
{
MemoryStream memStream = new MemoryStream(attachment.Value);
mailMessage.Attachments.Add(new Attachment(memStream, attachment.Key));
}
}
mailClient.Send(mailMessage);
}
When sending through a POP3 client the email that is sent has the expected format, however when I send through the Azure SendGrid module, each new line is doubled up so there are two blank lines for every one in the source body string. Does anyone know how to circumvent this issue as I need (and want) to use SendGrid.
I see this very similar question SendGrid newline issue however the fix relates to PHP - I need the equivalent in C#

Ok, after several hours of investigation, within 5 minutes of posting the question I find the answer and its real simple, adding this to the mail client configuration sorts the issue perfectly:
mailMessage.BodyEncoding = Encoding.UTF8;

Related

C# mailing with BCC to PHP ready mail server using Custom Headers

Got an issue about C# mailing.
According to rfc format has no problem when BCC added to the custom header!
However according to MSDN BCC info that is added to custom header will be deleted!
So in this particular situation I have to send an email trough C# code to a server that accepts BCC info in the custom header only...
How can I achive that? So far what I've tried is below;
// Mail Configurations
MailMessage mail = new MailMessage();
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.None;
mail.Priority = MailPriority.Normal;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.HeadersEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.BodyTransferEncoding = System.Net.Mime.TransferEncoding.Base64;
mail.From = new MailAddress(FROM, FROM, System.Text.Encoding.UTF8); // From
mail.To.Add(new MailAddress(TO, TO, System.Text.Encoding.UTF8)); // EmailTo
// mail.CC.Add(new MailAddress(CC, CC, System.Text.Encoding.UTF8)); // CC
// mail.Bcc.Add(new MailAddress(BCC, BCC, System.Text.Encoding.UTF8)); // BCC
mail.Headers.Add("BCC", BCC); // BCC 2nd method adding in headers as PHP does
mail.Subject = Subject;
mail.IsBodyHtml = true;
mail.Body = "<div>Hello World!<div>";
mail.Attachments.Add(new Attachment(FileName));
// SMTP Configurations
SmtpClient SmtpServer = new SmtpClient(SMTP, PORT);
SmtpServer.UseDefaultCredentials = false;
SmtpServer.DeliveryFormat = SmtpDeliveryFormat.International;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.EnableSsl = true;
SmtpServer.Credentials = new NetworkCredential(SMTPUser, SMTPPass);
// Send Mail
SmtpServer.Send(mail);
// Clear All
mail.To.Clear();
mail.Bcc.Clear();
mail.Headers.Clear();
mail.Attachments.Clear();
Edit: Depending on the comments I've also tried MailKit library.
It had no effect on BCC the code I've used is;
// Mail
var message = new MimeMessage();
message.From.Add(new MailboxAddress(System.Text.Encoding.UTF8, FROMName, FROM));
message.To.Add(new MailboxAddress(System.Text.Encoding.UTF8, TO, TO));
message.Cc.Add(new MailboxAddress(System.Text.Encoding.UTF8, CC, CC));
message.Bcc.Add(new MailboxAddress(System.Text.Encoding.UTF8, BCC, BCC));
message.Subject = Subject;
message.Priority = MessagePriority.Normal;
message.Importance = MessageImportance.Normal;
message.XPriority = XMessagePriority.Normal;
// With Body Builder
var builder = new BodyBuilder();
builder.HtmlBody = "<div> Hello World! </div>"; // Set the html version of the message text
builder.Attachments.Add(FileName); // We may also want to attach some files
message.Body = builder.ToMessageBody(); // Now we just need to set the message body and we're done
// SMTP connect
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect(SMTP, SMTPPort, false);
// Note: only needed if the SMTP server requires authentication
client.Authenticate(SMTPUser, SMTPPass);
client.Send(message);
client.Disconnect(true);
}
I'm not sure if I'm following along correctly, but it sounds like you need to send a message where the raw Bcc: header is sent in the headers to the SMTP server?
This is highly non-standard and very suspect since the whole point of the Bcc: header is that it gets stripped at send time because recipients in the Bcc: header field are meant to be BLIND Carbon Copy recipients (aka, hidden to everyone who receives the message).
That said... if you REALLY REALLY do need to include the Bcc: header in the message data that gets uploaded to the SMTP server, then you can do this:
var options = FormatOptions.Default.Clone ();
options.HiddenHeaders.Add (HeaderId.ContentLength);
options.HiddenHeaders.Remove (HeaderId.ResentBcc);
options.HiddenHeaders.Remove (HeaderId.Bcc);
options.NewLineFormat = NewLineFormat.Dos;
client.Send (options, message);
Note: Currently the Resent-Bcc and Bcc headers are not hidden in the default FormatOptions, I just added those .Remove() calls to illustrate how to control which headers get hidden vs not.
The SmtpClient.Send() methods that do not take a FormatOptions argument use an internal FormatOptions that add the Bcc, Resent-Bcc, and Content-Length headers to the hidden list.

best way to send email in asp net c# MVC with attachment between Thread or Async

I want to know the best way for sending emails with attachment between Thread OR Async in ASP.net MVC C#.
OR
Do I need to use other library for sending email with attachments.
If someone provide sample working code. It would be great.
Thanks
using(var client = new SmtpClient())
{
var message = new MailMessage(from, to);
message.body = "body text";
message.subject = "subject text";
message.Attachments.Add(new Attachment("path to file"));
await client.SendAsync(message);
}

SMTP Permission Error

I'm using system.net.mail and have a textbox that users can enter their email address and a file gets attached and sent to them. When I test this in my custom box with Server 2008 I get the following error:
Request for the permission of type 'System.Net.Mail.SmtpPermission....at System.Security.CodeAccessSecurityEngine.Check
Do I have to configure something specifically on the server to allow? Or is it a code error?
string strto = txtTo.Text;
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("serveremail");
mail.To.Add(strto);
//set the content
mail.Subject = "subject";
//Get some binary data
byte[] byteArray = Encoding.ASCII.GetBytes(result);
//save the data to a memory stream
using (MemoryStream ms = new MemoryStream(byteArray))
//create the attachment from a stream. Be sure to name the data with a file and
//media type that is respective of the data
mail.Attachments.Add(new Attachment(ms, "test.txt", "text/plain"));
//send the message
SmtpClient smtp = new SmtpClient("server");
smtp.Send(mail);
This looks like it could be a permission issue when trying to access the attachment from the steam. What happens if you explicitly state credentials?

setting mail header in c#

hi i need to set header content type in c#.
when i send mail from c#, i'm getting the mail with html tags. how can set content type in mail sending code?
In case that you asking how can I send email in c#:
MailMessage mail = new MailMessage();
mail.To = "me#mycompany.com";
mail.From = "you#yourcompany.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
mail.IsBodyHtml = false;
SmtpMail.SmtpServer = "localhost"; //your real server goes here
SmtpMail.Send( mail );
Source: here.
MailMessage mail = new MailMessage();
// need to set this property
mail.IsBodyHtml = false;
For more alterations, you can do with templates in your email, see
Can I set up HTML/Email Templates in
C# on ASP.NET?
Hope this helps

SmtpClient sends email to junk

I tried to send email from c# using SmtpClient.Send() but it always goes to the junk box. It works fine if I send it from Outlook. Is there anyway to solve this? Someone told me to modify the email header but I don't know how.
Thanks in advance.
Here is my code
SmtpClient client = new SmtpClient();
client.Host = "smtp.server.com";
client.Credentials = new System.Net.NetworkCredential("user", "password");
MailAddress mailFrom = new MailAddress("mymail#server.com");
MailAddress mailTo = new MailAddress("yourmail#server.com");
MailAddress mailReply = new MailAddress("mymail#server.com");
MailMessage message = new MailMessage(mailFrom, mailTo);
message.Body = "This is a test message.";
message.Subject = "test message";
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.BodyEncoding = System.Text.Encoding.UTF8;
client.Send(message);
a) The code sample doesn't actually use the mailReply address.
b) The problem will probably disappear when you send a more realistic message. If it doesn't then you will have to find out why the message is being marked junk, fishing a message from the spambox and looking at the headers or something like that.
Spam filters may discard messages that have invalid entries.
Try putting in valid (existing) addresses of sender, reply and from.

Categories