C# mvc2 create an plain text email in code - c#

I need to create an plain-test email in code. This is required because the information in the email will be read by an application.
I've created the following value in an constant string as setup for my email. These are the fields that I want to be in the e-mail because the application requires them.
public static string TestMail = #"
[Begin Message]
Name = {0}
Phone = {1}
Postalcode = {2}
HomeNumber = {3}
[End message]";
When sending the email using the code below, the application which needs to read information from the email, receives it as following;
=0D=0A        [Begin Message]=0D=0A        Name =3D nam=
e=0D=0A        Phone =3D 0612345678=0D=0A        Postalcode =3D =
1234ab=0D=0A        HomeNumber =3D 5=0D=0A        [End messa=
ge]=0D=0A       =20
The code I used to send this email is as following;
var mailBody = String.Format(Constants.TestMail, name, phone, postalCode, homeNumber);
var mail = new MailMessage
{
Subject = Constants.Subject,
Body = mailBody,
IsBodyHtml = false,
};
mail.To.Add(receveiver);
var smtpClient = new SmtpClient();
smtpClient.Send(mail);
This isn't the result I expected and after digging around a bit I found out that the problem lied in the fact that it still seems to be an HTML-email while I need it to be plain-text. While reading about this problem I found this example in VB.net on the internet. So i modified the constant to the one below;
public static string TestMail = #"[Begin message]\r\nName = {0}\r\nPhone = {1}\r\nPostalcode = {2}\r\nHomenumber = {3}\r\n[End message]";
Then I used the following code to create and sent the email to my client (testing in outlook)
var mail = new MailMessage
{
Subject = Constants.Subject,
};
var alternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailBody, Encoding.ASCII,"text/plain");
mail.AlternateViews.Add(alternateView);
mail.To.Add(receveiver);
var smtpClient = new SmtpClient();
smtpClient.Send(mail);
After running this code i'm receiving an email in my outlook (can't test the application at the moment) containing the content below;
[Start message]\r\nName = John\r\nPhone = 0612345678\r\nPostalcode = 1234ab\r\nHomeNumber = 5\r\n[End Message]
The last result doesn't seem an plain-text email to me. Is it just outlook 2007 having problems to show the email? Or am I still missing something? I hope someone can help me out here and can tell me what's going wrong.

You should remove # character because then it will correctly handle escape characters. If you have # then all escape characters are treated as a plain text instead of new line etc.

Related

C# Exchange EmailMessage Send: As soon as I add an attachement, I get error "No mailbox with such guid"

In my application I use some code to send automated mails over our Exchange server.
My current goal is to send a HTML mail with some pictures as a handout. That pictures shall be attachments of the mail.
To this point the code is working (I have changes internal names in the code example):
ExchangeService MailClient = new ExchangeService
{
UseDefaultCredentials = true,
Url = new Uri("https://<domain.of.company>/EWS/Exchange.asmx")
};
EmailMessage msg = new EmailMessage(MailClient);
msg.ToRecipients.Add(new EmailAddress(user.EmailAddress));
msg.Sender = new EmailAddress("sender#domain.of.company");
msg.Subject = "Some text here";
MessageBody Body = new MessageBody
{
BodyType = BodyType.HTML,
Text = NameOfApplication.Properties.Resources.Embedded_HTML_File
};
msg.Body = Body;
msg.SendAndSaveCopy(new FolderId(WellKnownFolderName.SentItems, "sender#domain.of.company")));
With this code the E-Mail get saved in the "Sent" folder and arrives the target mailbox. Success so far.
But as soon I add an attachement by this (no other changes were made)
msg.Attachments.AddFileAttachment(AppContext.BaseDirectory + "Logo.jpg");
SendAndSaveCopy throws an exception with the description "No mailbox with such guid."
When I comment out the AddFileAttachment line the code is working again.
Any idea whats wrong with attachments?
Found the solution. Reading tooltips might help.
Maybe the day will come, when Microsoft will change SendAndSaveCopy to include this step.
But yes: The error message is misleading.

Not getting any clue to integrate Gmail API using .NET framework in vs2017. I wanted to send the input data of the Web form to a user's email .

The official Gmail API documentation is horrendous. Not getting any clue to integrate Gmail API using .NET framework in vs2017. I wanted to send the input data of the Web form to a user's email.
It would be a three step process -
Define an HTML template which which describes how your mail should be presented.
Write a small c# code to replace all place holders like your form fields , user name, etc.
private string createEmailBody(string userName, string title, string message)
{
string body = string.Empty;
//using streamreader for reading my htmltemplate
using(StreamReader reader = new StreamReader(Server.MapPath("~/HtmlTemplate.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{UserName}", userName); //replacing the required things
body = body.Replace("{Title}", title);
body = body.Replace("{message}", message);
//// Instead of message add you own parameters.
return body;
}
When form is submitted, call step 2 code first. Then use it's output to set mail body.
Code would be something like -
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
/// This mail from can just be a display only mail I'd
string emailFrom = "no-reply#gmail.com";
string subject = "your subject";
string body = createEmailBody();
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
/// Add more to IDs if you want to send it to multiple people.
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// This is required to keep formatting of your html contemts
/// Add attachments if you want, this is optional
mail.Attachments.Add(new Attachment(yourfilepath));
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(your-smtp-account-email, your-smtp-account-password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
Refer this link for working example
https://www.c-sharpcorner.com/UploadFile/33b051/sending-mail-with-html-template/
EDIT: For using GMail API
Using GMAIL APIs you will need two nuget packages:
1. Install-Package Google.Apis.Gmail.v1
2. Install-Package AE.Net.Mail
Code is very similar to what we have for normal SMTP mail send. It is explained at: http://jason.pettys.name/2014/10/27/sending-email-with-the-gmail-api-in-net-c/

Umlauts in iPhone v-card

I need to send e-mails to iPhone users with .vcf files for adding contacts. The problem is that contact name has umlaut symbols and they displays incorrectly.
Also I noticed that if I send the same text in the body of email or open composed vcf file in notepad the symbols displays correctly.
public void SendEmail(string to, string subject, string body)
{
using (var message = new MailMessage())
{
message.To.Add(new MailAddress(to));
message.Subject = subject;
message.SubjectEncoding = Encoding.UTF8;
message.BodyEncoding = Encoding.UTF8;
message.HeadersEncoding = Encoding.UTF8;
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(body)))
{
string attachamentName = string.Format("{0}.vcf", subject);
Attachment attachment = new Attachment(stream, MediaTypeNames.Application.Octet) { Name = attachamentName };
attachment.ContentDisposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
using (var client = new SmtpClient())
{
client.Send(message);
}
}
}
}
Can someone please help me?
UPDATE: Sorry, have to edit code sample, I've accidentally submit the wrong one.
UPDATE #2: It looks like it is not only iPhone problem, Outlook also does not recognize umlauts.
UPDATE #3: Added full code for sending e-mail
Try changing to:
BEGIN:VCARD\r\nVERSION:2.1\r\nN;CHARSET=LATIN1:Fältskog;Agnetha\r\nFN;CHARSET=LATIN1:Agnetha Fältskog\r\nORG:\r\nTITLE:\r\nEND:VCARD
Just from reading elsewhere - looks like the format needs this CHARSET tag on each field, and seems that either LATIN1 or iso-8859-1 character sets, rather than utf-8 need to be specified for these.
Try to change
VERSION:2.1\r\n
to
VERSION:3.0\r\n
After that you don't need CHARSET-Tags for fields with umlauts,
it should work as expected.

MailChimp (Mandrill) for .NET why email includes Image?

I'm using MailChimp for .NET from this nuget https://www.nuget.org/packages/mcapi.net/1.3.1.3 and tried sending emails. But the email I received include image (unseen image) even if I'm just sending simple html. Has anyone encountered it? How to get rid of this unseen image? Please help.
Below is my sample email message.
var api = new MandrillApi("XXXXXXXXXXX");
var recipients = new List<Mandrill.Messages.Recipient>();
var name = string.Format("{0} {1}", "Jobert", "Enamno");
recipients.Add(new Mandrill.Messages.Recipient("recipient#gmail.com", name));
var message = new Mandrill.Messages.Message()
{
To = recipients.ToArray(),
FromEmail = "admin#mysite.com",
Subject = "Test Email",
Html = "<div>Test</div>"
};
MVList<Mandrill.Messages.SendResult> result;
result = api.Send(message);
Received Email
When clicked No image shown
You're seeing this because Mandrill uses a small invisible graphic for open tracking. You'd want to either disable open tracking in the API call you're making or on the Sending Options page in your Mandrill account.

Truncate e-mail text string at the # portion in C#

I have a situation in ASP.NET C# wherein for example I have the email address hello#gmail.com but I need to have the #gmail.com portion removed for all email input. Please help. Thanks :)
You can use MailAddress Class (System.Net.Mail):
string mailAddress = "hello#gmail.com";
var mail = new MailAddress(mailAddress);
string userName = mail.User; // hello
string host = mail.Host; // gmail.com
string address = mail.Address; // hello#gmail.com
In the case of wrong e-mail address (eg. lack of at sign or more than one) you have to catch FormatException, for example:
string mailAddress = "hello#gmail#";
var mail = new MailAddress(mailAddress); // error: FormatException
If you don't want to verify e-mail address, you can use Split method from string:
string mailAddress = "hello#gmail.com";
char atSign = '#';
string user = mailAddress.Split(atSign)[0]; // hello
string host = mailAddress.Split(atSign)[1]; // gmail.com
email = email.Substring(0, email.IndexOf('#'));
Like this:
new MailAddress(someString).User
If the email address is invalid, this will throw an exception.
If you also need to validate the email address, you should write new MaillAddress(someString) inside of a catch block; this is the best way to validate email addresses in .Net.

Categories

Resources