MailKit receive emails doesn't show message.Body - c#

I'm receiving emails OK, except that message.TextBody is showing a blank when there is a message present.
message.HtmlBody shows the body text amongst a whole lot of html stuff, obviously, but I'm looking for message.TextBody.
message.TextBody.ToString() shows an error
Object reference not set to an instance of an object
I'm using the following code:
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
client.Connect("pop.gmail.com", 995, true);
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate("aaaa#gmail.com", "ssss");
gstrEmailMessages = gstrEmailMessages + client.Count + "\n";
//Fetch emails:
for (int i = 0; i < client.Count; i++)
{
var message = client.GetMessage(i);
gstrEmailMessages = gstrEmailMessages + "Subject: " + message.Subject + "\n";
gstrEmailMessages = gstrEmailMessages + "TextBody: " + message.TextBody + "\n";
gstrEmailMessages = gstrEmailMessages + "HtmlBody: " + message.HtmlBody + "\n";
}
//Disconnect connection:
client.Disconnect(true);
Why does message.TextBody show a blank?

Not all messages will have both an HTML and a plain-text body. In fact, it's possible for some messages to have neither.
In general, though, most messages will have at least 1 of those.

Related

Using apostrophe in email subject while sent email via gmail api creating an issue

While sent email using below subject which apostrophe replacing with another characters
Actual Subject : We’ll make 100,800 cold calls for you
Mail Shows Subject : We’ll make 100,800 cold calls for you
Issue happens when I'm sent email via api , when sent email from SMTP it's working fine
Please check my api code below
string msg = "From: " + FromName + "<" + From + ">" + " \r\n" +
"To: " + ToName + "<" + To + ">" + " \r\n" +
"BCC: " + BCCEmail + " \r\n" +
"Subject: " + Subject + " \r\n" +
"Message-ID: mID_" + messageID + "\r\n" +
"References: "+encryptMessageID + "\r\n" +
"In-Reply-To: " + encryptMessageID + "\r\n" +
"Content-Type: " + contentType + "; charset=us-ascii\r\n\r\n" + Body;
dynamic objSendMsg = new { raw = commonFunction.Base64UrlEncode(msg) };
if (!string.IsNullOrEmpty(messageThreadID))
objSendMsg = new { raw = commonFunction.Base64UrlEncode(msg), threadId = messageThreadID };
var _objSendMsg = JsonConvert.SerializeObject(objSendMsg);
var strSendMsg = new StringContent(_objSendMsg, UnicodeEncoding.UTF8, "application/json");
When same content i'm applying in body with apostrophe working fine for body
Please check attached screenshot
Email copy
You need to base64_encode of the subject header your sending it as plain text. the API is getting confused.
Subject: " + Convert.ToBase64String(Subject) + " \r\n" +

Property or indexer "Attachments" cannot be assigned to -- it is read only

I´m trying to send mail with image attachment, but it still throwing error
(*Property or indexer "Attachments" cannot be assigned to -- it is read only *)
string pathToPic = #"c:\MyDir\Img\img"+ automaticalyGeneratedNumber.toString() + ".png";
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = Environment.MachineName,
Body = "PC NAME : " + Environment.MachineName + "\r\nIP ADRESS : " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1],
Attachments = new Attachment(#"c:\MyDir\Img" + "/img" + (Saving.CountImagesTaken(#"c:\MyDir\Img") - 1).ToString() + ".png"),
})
{
smtp.Send(message);
}
Why complicate the code like that. You need to use message.Attachments.Add since the Attachments property is read-only :
var message = new MailMessage(fromAddress, toAddress)
{
Subject = Environment.MachineName,
Body = "PC NAME : " + Environment.MachineName + "\r\nIP ADRESS : " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1],
};
message.Attachments.Add(new Attachment(#"c:\MyDir\Img" + "/img" + (Saving.CountImagesTaken(#"c:\MyDir\Img") - 1).ToString() + ".png"));
using (message)
{
smtp.Send(message);
}

.Net.Mail body message lose the format while is sent c# .net

I'm using a string builder to create a body message while trying to do something.
the issue es I'm getting the value from the string builder and this one is formatted.
Example from my string builder:
Following files were attached by email:
1. C:\SALASFRI2_20150824094158_ScrubLog.txt - Record Count: 8
2. C:\SALASFRI2_20150824102328_ScrubLog.txt - Record Count: 8
3. C:\SALASFRI2_20150824102516_ScrubLog.txt - Record Count: 8
4. C:\SALASFRI2_20160121125353_ScrubLog.txt - Record Count: 8
5. C:\SALASFRI2_20160121125659_ScrubLog.txt - Record Count: 8
===================================================
Total Files: 5
Please contact your system administrator for any further assitance.
That's exactly how the stringbuilder looks, but when the email arrived, it lose their format as follow:
do you know if there is a property to don't lose the format when it arrive to my email?
This is my code:
if (Notification.IncludeFileName || Notification.IncludeRecordCount)
{
BodyMessage.Append("Following files were attached by email: \n");
for (int index = 0; index < NumberOfFiles; index++)
{
if (Notification.IncludeFileName && Notification.IncludeRecordCount)
BodyMessage.Append((index + 1) + ". " + LocalFiles[index] + " - Record Count: " + File.ReadLines(LocalFiles[index]).Count() + "\n");
else
BodyMessage.Append((index + 1) + ". " + LocalFiles[index] + File.ReadLines(LocalFiles[index]).Count() + "\n");
}
}
if (Notification.IncludeNumberOfFiles)
{
BodyMessage.Append("\n===================================================\n\n");
BodyMessage.Append("Total Files: " + NumberOfFiles + "\n");
}
BodyMessage.Append("\nPlease contact your system administrator for any further assitance.");
////////////////////END OF SUBJECT AND BODY MAIL MESSAGE VALIDATION
////////............SEND THE ATTACHMENTS THROUGH EMAIL................///////////
try
{
MailMessage Email = new MailMessage();
SmtpClient smtp = new SmtpClient(AppConfiguration.SMTPServer);
Email.From = new MailAddress(AppConfiguration.EmailAddress);
Email.To.Add(protocol.SMTPEmailList);
Email.Subject = EmailSubject;
Email.Body = BodyMessage.ToString();
if (directories.Zip)
Email.Attachments.Add(new Attachment(ZipName));
else
foreach (var attachment in LocalFiles)
{
Email.Attachments.Add(new Attachment(attachment));
}
smtp.Port = AppConfiguration.SmtpPort;
smtp.UseDefaultCredentials = true;
smtp.Send(Email);
Email.Dispose();
You probably need to use "\r\n" as your newline sequence instead of just "\n".

Making a connection to IRC through SSL

Could someone please show me an example of how to make an SSL connection to an IRC server?
I have tried reading about SslStreams but I just don't get it. I am able to connect to IRC without SSL using this:
sock.Connect(server, port);
if (!sock.Connected) {
Console.WriteLine("Failed to connect!");
return;
}
input = new System.IO.StreamReader(sock.GetStream());
output = new System.IO.StreamWriter(sock.GetStream());
output.Write("USER " + nick + " 0 * :" + owner + "\r\n" + "NICK " + nick + "\r\n");
output.Flush();
//Process each line received from irc server
for (buf = input.ReadLine(); ; buf = input.ReadLine()) {
//Display received irc message
//Console.WriteLine(buf);
if (buf.Split(' ')[1] == "332") {
Console.WriteLine(buf.Split(new char[] { ' ' }, 5)[4]);
}
//Send pong reply to any ping messages
if (buf.StartsWith("PING ")) {
output.Write(buf.Replace("PING", "PONG") + "\r\n"); output.Flush();
}
if (buf[0] != ':') continue;
if (buf.Split(' ')[1] == "001") {
output.Write(
"MODE " + nick + " \r\n" +
"JOIN " + chan + "\r\n"
);
output.Flush();
}
}
}
}
Try this:
conn, err = tls.Dial("tcp", HOST+":"+PORT, &tls.Config{InsecureSkipVerify: true})

Email formatting in code behind

I need to send an email to a customer that has just completed a transaction but I am having some difficulties in drafting out the format in code behind, this is my code, apparently it's appearing as one straight line of text in the body of my mail, how can I format it in such a way it appears something like, any help is appreciated, thanks :
Thank you for shopping with us. Your purchase details are as follow:
Product ID Model Number Model Name Unit Cost Quantity ItemTotal
357 P1 AK47 Rifle(free 30 * 7.62) $2.99 1 2.99
362 XT3893 Mirage stealth tank $500000.99 1 500000.99
Total:$500002.99
This is my code:
MembershipUserCollection users = Membership.GetAllUsers();
MembershipUser u = users[UserName];
MailMessage mail = new MailMessage();
mail.To.Add(u.Email);
mail.From = new MailAddress("me#hotmail.com");
mail.Subject = "Purchase invoice" + newOrder.OrderID;
string bodyText = "";
double unitQtyPrice = 0;
double totalPrice = 0;
foreach (var cItem in cartList)
{
Math.Round(cItem.UnitCost, 2);
bodyText = bodyText + '\n'
+ cItem.ProductID.ToString() + '\t'
+ cItem.ModelName + '\t'
+ cItem.ModelNumber + '\t'
+ cItem.UnitCost.ToString() + '\t'
+ cItem.Quantity.ToString() + '\t';
unitQtyPrice = cItem.Quantity * (double)cItem.UnitCost;
totalPrice += unitQtyPrice;
}
Math.Round(totalPrice, 2);
mail.Body = "Thank you for shopping with us. Your purchase details are as follow:"
+ '\n' + "ProductID:" + '\t' + "ModelName" + '\t' + "ModelNumber" + '\t' + "UnitPrice" + '\t' + "Quantity"
+ '\n' + bodyText + '\n' + '\n' + '\t' + '\t' + "Total Price:" + totalPrice ;
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.live.com", 587);
client.EnableSsl = true; //ssl must be enabled for hotmail
NetworkCredential credentials = new NetworkCredential("me#hotmail.com", "xxxx");
client.Credentials = credentials;
try
{
client.Send(mail);
}
catch (Exception exp)
{
throw new Exception("ERROR: Fail to send email - " + exp.Message.ToString(), exp);
}
You have it set to HTML, which is whitespace-insensitive. If you want it to be sent as plaintext with line breaks and all, don't set IsBodyHtml.
Alternatively, you can include actual HTML markup to lay out your email, which may be a better solution.
Just write you mail.Body part in an HTML language...
and set
mail.IsBodyHtml = true;

Categories