how to convert non-mime message to mime mail message in c# - c#

i got a mail message which is not a MIME message
can not get Content-Type
can not get attachment
how to convert this message into MIME message
foreach (AE.Net.Mail.Lazy<MailMessage> message in messages)
{
MailMessage m = message.Value;
string sender = m.From.Address;
ICollection<Attachment> cc = m.Attachments;
foreach (Attachment aa in cc)
{
System.IO.File.WriteAllBytes(#"C:\Users\LAB-User2\Desktop\EmailAttachments\" + aa.Filename, aa.GetData());
}
}
Update
does this disposition work for non-mime message?
public string GetDisposition()
{
return this["Content-Disposition"]["boundary"];
}
string disposition = Headers.GetDisposition();
if (!string.IsNullOrEmpty(disposition))
{
//else this is a multipart Mime Message
using (var subreader = new StringReader(line + Environment.NewLine + reader.ReadToEnd()))
ParseMime(subreader, disposition);
}
else
{
//SetBody((line + Environment.NewLine + reader.ReadToEnd()).Trim());
}
can i send non-mime email to myself ? so that i can receive mime format email?
when i try this, i can not email to myself
ImapClient imap = new ImapClient("imap.gmail.com", "hello#gmail.com", "pwd", ImapClient.AuthMethods.Login, 993, true, true);
//imap.Connect("imap.gmail.com", 993, true, true);
imap.SelectMailbox("INBOX");
//MailMessage[] mm = imap.GetMessages(imap.GetMessageCount() - 1, imap.GetMessageCount() - 10, false, false);
AE.Net.Mail.Lazy<AE.Net.Mail.MailMessage>[] messages = imap.SearchMessages(SearchCondition.Unseen(), false);
// Run through each message:
foreach (AE.Net.Mail.Lazy<AE.Net.Mail.MailMessage> message in messages)
{
AE.Net.Mail.MailMessage mm = message.Value;
//create the mail message
//var mail = new MailMessage();
var mail = new System.Net.Mail.MailMessage();
//set the addresses
mail.From = new MailAddress("me#mycompany.com", "demo");
mail.To.Add("hello#gmail.com");
//set the content
mail.Subject = "This is an email";
//first we create the Plain Text part
//var plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
//var htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");
ICollection<AE.Net.Mail.Attachment> cc = mm.AlternateViews;
foreach (AE.Net.Mail.Attachment aa in cc)
{
try
{
System.IO.File.WriteAllBytes(#"C:\Users\LAB-User2\Desktop\EmailAttachments\" + aa.Filename, aa.GetData());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//mail.AlternateViews.Add(b);
}
var plainView = AlternateView.CreateAlternateViewFromString(mm.Raw, null, "text/plain");
mail.AlternateViews.Add(plainView);
//send the message
var smtp = new SmtpClient("smtp.gmail.com", 587); //specify the mail server address
smtp.Credentials = new System.Net.NetworkCredential("hello#gmail.com", "pwd");
smtp.EnableSsl = true;
smtp.Send(mail);
smtp = null;
mail.Dispose();

You can use this sample:
//create the mail message
var mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me#mycompany.com");
mail.To.Add("you#yourcompany.com");
//set the content
mail.Subject = "This is an email";
//first we create the Plain Text part
var plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
var htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
//send the message
var smtp = new SmtpClient("127.0.0.1"); //specify the mail server address
smtp.Send(mail);

Related

Adding attachments using url in mail with C sharp

I can send attachments with URLs, But, looking for support to send a file with an attachment. that too should download from url and attach with mail.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#email.com");
//to mail address
mail.To.Add(txtEmail.Text);
//Add the Attachment
mail.Attachments.Add(data);
//set the content
mail.Subject = txtSubject.Text;
mail.Body = "Kindly find the below attachments with the link, https://www.python.org/static/img/python-logo#2x.png";
//send the message
SmtpClient smtp = new SmtpClient("*****.********.net");
NetworkCredential Credentials = new NetworkCredential("mymail#email.com", "********");
smtp.Credentials = Credentials;
smtp.Send(mail);
Here I'm sending mail with URL as a file,
But I want to attach a file instead of sending a link
The sample URL was added as an image link.. But I wanted to add a pdf link..
In this case, I want to download a file and attach it with mail,
I use it mostly in my all projects it's working fine. its with base 64
First, make sure your Gmail account is turned on for sending emails.
public static async Task SendEmail(string toUser, string subject, string body
, string username, string password, string port, string smtpServer, string ccUsers = "", string base64Url = "")
{
var toAddress = new System.Net.Mail.MailAddress(toUser, toUser);
System.Net.Mail.MailMessage emessage = new System.Net.Mail.MailMessage();
emessage.To.Add(toAddress);
if (!string.IsNullOrEmpty(ccUsers))
{
string[] ccIds = ccUsers.Split(',');
foreach (string item in ccIds)
{
emessage.CC.Add(new System.Net.Mail.MailAddress(item));
}
}
emessage.Subject = subject;
emessage.From = new System.Net.Mail.MailAddress(username);
emessage.Body = body;
emessage.IsBodyHtml = true;
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
if (!string.IsNullOrEmpty(base64Url))
{
base64Url = base64Url.Replace("data:image/jpeg;base64,", "");
var imageBytes = Convert.FromBase64String(base64Url);
var stream = new MemoryStream(imageBytes);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg);
System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(stream, ct);
at.ContentDisposition.FileName = "Invoice.jpeg";
emessage.Attachments.Add(at);
}
var netCredential = new System.Net.NetworkCredential(username, password);
sc.Host = smtpServer;
sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
sc.UseDefaultCredentials = false;
sc.Credentials = netCredential;
sc.EnableSsl = true;
sc.Port = Convert.ToInt32(port);
await sc.SendMailAsync(emessage);
}
It works fine and mail directly reaches inbox instead of spam.. also can able to attach files from serverpath. Thank you everyone who wish to answer my questions..
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#gmail.com");
mail.To.Add("tomail#gmail.com");
//set the content
string filename = "Report1";
string fileurl = Server.MapPath("..");
fileurl = fileurl + #"\mailserver\pdf\generated\" + filename + ".pdf";
//mail.Attachments.Add(new Attachment(fileurl));
if (!string.IsNullOrEmpty(fileurl))
{
Attachment attachment = new Attachment(fileurl, MediaTypeNames.Application.Pdf);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(fileurl);
disposition.ModificationDate = File.GetLastWriteTime(fileurl);
disposition.ReadDate = File.GetLastAccessTime(fileurl);
disposition.FileName = Path.GetFileName(fileurl);
disposition.Size = new FileInfo(fileurl).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
mail.Attachments.Add(attachment);
}
mail.Subject = "Subject Text";
mail.Body = "Body Text";
//send the message
SmtpClient smtp = new SmtpClient("smtpout.****.******server.net");
NetworkCredential Credentials = new NetworkCredential("mymail#gmail.com", "Password#123");
smtp.Credentials = Credentials;
//smtp.EnableSsl = true;
smtp.Send(mail);
Response.Write("<center><span style='color:green'><b>Mail has been send successfully!</b></span></center>");
}
catch (Exception ex)
{
//Response.Write("<center><span style='color:red'><b>"+ ex + "</b></span></center>");
Response.Write("<center><span style='color:red'><b>Failed to send a mail...Please check your mail id or Attachment missing</b></span></center>");
}
}

Send e-mail with image on body

I want to send an e-mail with a logo at the top of the body. This is my method:
public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo style=\"height: 50px;\"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = port;
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
The method is sending the e-mail, but the image is being sent as an attachment. I've tried to do this:
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"), MediaTypeNames.Image.Jpeg);
But when I add "MediaTypeNames.Image.Jpeg" in this line, the e-mail is sent without the image at all.
Someone can help me on this? Thanks in advance!
You could convert your image to base64 and add that in src or you could just give the page where is the image is located.
You could try the library MailKit. Sending embedded images works well with this library.
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Png);
stream.Position = 0;
var resource = builder.LinkedResources.Add(contentId, stream);
resource.ContentId = contentId;
// in the email message, there is img with src="cid:contentId"
Another example of embedding images is here.
You can use it :
public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo style=\"height: 50px;\"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = 0; //add port here
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
//add file here
Attachment attachment = new Attachment("c://image");
attachment.ContentDisposition.Inline = true;
message.Attachments.Add(attachment);
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}

Converting SMTP Sendgrid to Sendgrid API

Currently replacing the old SMTP Sendgrid to API Sendgrid and I noticed that there are some differences in their code.But I was thinking that since they are both sendgrid it will just work. What I did is to add this SendGridClient.SendEmailAsync(Message); in the end. But it says
cannot convert from system.net.mail.mailmessage to sendgrid.helpers.mail.sendgridmessage
Is this the correct way of converting it?
Below is the code.
try
{
string SendGridKey = ConfigurationManager.AppSettings["SendGridKey"];
var SendGridClient = new SendGridClient(SendGridKey);
using (MailMessage MessageContent = new MailMessage())
{
MessageContent.From = new MailAddress(From);
MessageContent.To.Add(new MailAddress(To));
MessageContent.Subject = Subject;
MessageContent.Body = (TextBody);
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView Alternate = AlternateView.CreateAlternateViewFromString(HtmlBody, mimeType);
Message.AlternateViews.Add(Alternate);
if (AttachedFileName == true)
{
Attachment AttachedFile = new Attachment(HttpRuntime.AppDomainAppPath + "Path\\" + AttachedFileName);
MessageContent.Attachments.Add(AttachedFile);
}
//using (SmtpClient Client = new SmtpClient())
//{
// Client.EnableSsl = true;
// Client.Send(MessageContent);
//}
SendGridClient.SendEmailAsync(Message);
}
return;
}
For sending mail using SendGrid API, you need to create com.sendgrid.Request object. Adding code for java:
import com.sendgrid.Content;
import com.sendgrid.Email;
import com.sendgrid.Mail;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.SendGrid;
Email from = new Email("<FROM_EMAIL>");
String subject = "<SUBJECCT>";
Email to = new Email("<TO_EMAIL>");
Content content = new Content("text/plain", message);
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid(SendGridKey);
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
sg.api(request);
log.info("Main sent successfully");
} catch (IOException ex) {
log.info("Error while sending mail: {}", ex.toString());
}

How to send email using GMAIL API having HTML body + attachment in ASP.NET

var msg = new AE.Net.Mail.MailMessage
{
Subject = subject,
Body = bodyhtml,
From = new System.Net.Mail.MailAddress("myemail")
};
foreach (string add in vendorEmailList.Split(','))
{
if (string.IsNullOrEmpty(add))
continue;
msg.To.Add(new System.Net.Mail.MailAddress(add));
}
msg.ReplyTo.Add(msg.From); // Bounces without this!!
msg.ContentType = "text/html";
////attachment code
foreach (string path in attachments)
{
var bytes = File.ReadAllBytes(path);
string mimeType = MimeMapping.GetMimeMapping(path);
AE.Net.Mail.Attachment attachment = new AE.Net.Mail.Attachment(bytes, mimeType, Path.GetFileName(path), true);
msg.Attachments.Add(attachment);
}
////end attachment code
var msgStr = new StringWriter();
msg.Save(msgStr);
Message message = new Message();
message.Raw = Base64UrlEncode(msgStr.ToString());
var result = gmailService.Users.Messages.Send(message, "me").Execute();
This code is working without attachment but with attachment instead of attachment directly byte[] is appearing in inbox.
If i remove msg.ContentType = "text/html" this line then it is working but html not rendering in email, appearing as plain text.
I want to send both HTML body and attachment, Please help.
MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.Body = bodyhtml;
mail.From = new MailAddress("myemail");
mail.IsBodyHtml = true;
foreach (string add in vendorEmailList.Split(','))
{
if (string.IsNullOrEmpty(add))
continue;
mail.To.Add(new MailAddress(add));
}
foreach (string add in userEmailList.Split(','))
{
if (string.IsNullOrEmpty(add))
continue;
mail.CC.Add(new MailAddress(add));
}
foreach (string path in attachments)
{
//var bytes = File.ReadAllBytes(path);
//string mimeType = MimeMapping.GetMimeMapping(path);
Attachment attachment = new Attachment(path);//bytes, mimeType, Path.GetFileName(path), true);
mail.Attachments.Add(attachment);
}
MimeKit.MimeMessage mimeMessage = MimeMessage.CreateFromMailMessage(mail);
Message message = new Message();
message.Raw = Base64UrlEncode(mimeMessage.ToString());
var result = gmailService.Users.Messages.Send(message, "me").Execute();
I found solution after lot of efforts. Instead of AE.Net.Mail.MailMessage used System.Net.Mail.MailMessage and MimeKit to convert it to raw string. And now html body with attachment is working fine.
try adding IsBodyHtml = true
new AE.Net.Mail.MailMessage
{
Subject = subject,
Body = bodyhtml,
From = new System.Net.Mail.MailAddress("myemail")
IsBodyHtml = true
};

Send HTML email via C# with SmtpClient

How do I send an HTML email? I use the code in this answer to send emails with SmtpClient, but they're always plain text, so the link in the example message below is not formatted as such.
<p>Welcome to SiteName. To activate your account, visit this URL:
http://SiteName.com/a?key=1234.
</p>
How do I enable HTML in the e-mail messages I send?
This is what I do:
MailMessage mail = new MailMessage(from, to, subject, message);
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);
Note that I set the mail message html to true: mail.IsBodyHtml = true;
I believe it was something like:
mailObject.IsBodyHtml = true;
IsBodyHtml = true is undoubtedly the most important part.
But if you want to provide an email with both a text/plain part and a text/html part composed as alternates, it is also possible using the AlternateView class:
MailMessage msg = new MailMessage();
AlternateView plainView = AlternateView
.CreateAlternateViewFromString("Some plaintext", Encoding.UTF8, "text/plain");
// We have something to show in real old mail clients.
msg.AlternateViews.Add(plainView);
string htmlText = "The <b>fancy</b> part.";
AlternateView htmlView =
AlternateView.CreateAlternateViewFromString(htmlText, Encoding.UTF8, "text/html");
msg.AlternateViews.Add(htmlView); // And a html attachment to make sure.
msg.Body = htmlText; // But the basis is the html body
msg.IsBodyHtml = true; // But the basis is the html body
Apply the correct encoding of the Mailbody.
mail.IsBodyHtml = true;
i have an idea , you can add a check box to your project for sending email as html as an option for user , and add this code to enable it :
MailMessage mail = new MailMessage(from, to, subject, message);
if(checkBox1.CheckState == CheckState.Checked )
{
mail.IsBodyHtml = true;
}
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);
If you are using Mailkit,We can use TextBody,HtmlBody and Both for message body. Just write this code. It will help you
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(senderName, sender#address.com));
mailMessage.Sender = new MailboxAddress(senderName, sender#address.com);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.HtmlBody = "Hello There";
mailMessage.Body = builder.ToMessageBody();
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("user#name.com", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Categories