Hi everyone I'm trying to send an email using the MimeKit but I'm trying to attach a .pdf file I have some problems:
This is how I'm trying to send it:
private bool EnviarMail(string file, string from, string to, string subject, string content, string name)
{
bool estado = false;
try
{
var mensaje = new MimeMessage();
mensaje.From.Add(new MailboxAddress(name, from));
mensaje.To.Add(new MailboxAddress("", to));
mensaje.Subject = subject;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = content;
bodyBuilder.Attachments.Add(file);
mensaje.Body = bodyBuilder.ToMessageBody();
using (var client = new SmtpClient("myHost", myPort))
{
client.Send(mensaje);
}
estado = true;
return estado;
}
catch (Exception ex)
{
return estado;
}
}
But I have this error on client.send(mensaje) line. It says:
Argument 1: cannot convert from 'MimeKit.MimeMessage' to ' System.Net.Mail.MailMessage'
How can I send this email correctly?
I tried what is was told here : Can I send files via email using MailKit?
But I couldn't do it for same error
The error indicates that you are using the wrong SMTP client!
You should be using the one that comes with MimeKit (MailKit.Net.Smtp.SmtpClient) and not the one in .NET (System.Net.Mail.SmtpClient)
Note that MimeKit and MailKit work hand-in-hand with MimeKit devoted to the parsing and handling of messages. Where as MailKit concerns the network aspects of sending and receiving messages.
Related
I am having an issue with SmtpClient in an ASP.NET web application.
I have a generic function that builds an email message and then sends it. The code is as follows:
public static bool SendMessage( string fromName, string toName, string subject, string body ) {
var smtpClient = new SmtpClient("server address here")
{
Port = 587,
Credentials = new NetworkCredential("user", "pass"),
EnableSsl = false,
};
var mailMessage = new MailMessage
{
From = new MailAddress("sender", "Testing"),
Subject = subject,
Body = body
};
mailMessage.To.Add ( new MailAddress(toName, "Valued Customer") );
try {
smtpClient.Send ( mailMessage );
return true;
}
catch (Exception ex) {
var error = $"ERROR :{ex.Message}";
return false;
}
}
The problem is, I get the following error when I call it:
Mailbox unavailable. The server response was: <email address being sent to> No such user here
Naturally I removed the value in the < >, but in the original error message it is the email address of the recipient. I almost think the SMTP server believes the recipient has to be a user on the system.
What can I try next? I even hard-coded email addresses in rather than using variables, thinking maybe there was some weird issue with that, but it didn't work.
The error is telling you that the the SMTP server does not have a user with that email address (usually it has to do with security around the FROM address). The SMTP server will not send email if it does not recognize the FROM address.
Solution, change your FROM. Example:
var mailMessage = new MailMessage
{
From = new MailAddress("tester", "test#adminsystem.com"),
Subject = subject,
Body = body
};
I've been working with Microsoft graph API to receive and reply to the mail.
I've successfully received and send mails, but as per Graph API docs in reply only a comment can be passed.
https://learn.microsoft.com/en-us/graph/api/message-createreply?view=graph-rest-1.0&tabs=cs
I've developed the send mail code as shown below:-
IList<Recipient> messageToList = new List<Recipient>();
User currentUser = client.Me.Request().GetAsync().Result;
Recipient currentUserRecipient = new Recipient();
EmailAddress currentUserEmailAdress = new EmailAddress();
EmailAddress recepientUserEmailAdress = new EmailAddress();
currentUserEmailAdress.Address = currentUser.UserPrincipalName;
currentUserEmailAdress.Name = currentUser.DisplayName;
messageToList.Add(currentUserRecipient);
try
{
ItemBody messageBody = new ItemBody();
messageBody.Content = "A sample message from Ashish";
messageBody.ContentType = BodyType.Text;
Message newMessage = new Message();
newMessage.Subject = "\nSample Mail From Ashish.";
newMessage.ToRecipients = messageToList;
newMessage.CcRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "abc.xyz#xxxx.com"
}
}
};
newMessage.Body = messageBody;
client.Me.SendMail(newMessage, true).Request().PostAsync();
Console.WriteLine("\nMail sent to {0}", currentUser.DisplayName);
}
catch (Exception)
{
Console.WriteLine("\nUnexpected Error attempting to send an email");
throw;
}
This code is working fine!!
Can someone please share how I can Reply to a mail with attachment and mailbody like I'm able to do in Send mail.
Thanks in advance.
You have to create a reply, add the attachment, and then send the message. With the basic basic /reply endpoint you cant do it.
E.g.:
Create the message draft using POST request
As a response you will get the whole message structure with id set to something like AQMkADAwATMwMAItMTJkYi03YjFjLTAwAi0wMAoARgAAA_hRKmxc6QpJks9QJkO5R50HAP6mz4np5UJHkvaxWZjGproAAAIBDwAAAP6mz4np5UJHkvaxWZjGproAAAAUZT2jAAAA. Lets refer to it as {messageID}.
After that you can create an attachment using POST request to https://graph.microsoft.com/beta/me/messages/{messageID}/attachments
-After step 2 you will see created message in your mailbox Drafts folder. To send it use https://graph.microsoft.com/beta/me/messages/{messageID}/send
Hope it helps.
I am working on a uwp app to send html email with embedded image. I was using EASendMail nuget pakage and it was fine after some time my app shows error:
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond. (Exception from
HRESULT: 0x8007274c)
I think the trial period has expired what should I do?
using EASendMailRT;
https://www.emailarchitect.net/easendmail/kb/csharp.aspx?cat=8
I can't find any alternative
try
{
string ToAddress = MailSendPage.toAddressTxtBox;
string Subject = MailSendPage.subjectTxtBox;
SmtpMail oMail = new SmtpMail("TryIt");
oMail.From = new MailAddress(username);
if(!String.IsNullOrEmpty(ToAddress)&& !String.IsNullOrEmpty(Subject))
{
oMail.To.Add(new MailAddress(ToAddress));
oMail.Subject = Subject;
EASendMailRT.SmtpClient oSmtp = new EASendMailRT.SmtpClient();
SmtpServer oServer = new SmtpServer(host);
oServer.User = username;
oServer.Password = password;
oServer.Port = port;
if (IsStackPanalHasImg() == true)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
string[] files = Directory.GetFiles(localFolder.Path + #"\ProjectImages");
foreach (string eachfile in files)
{
foreach (string name in covertToHtml.ControlName)
{
string pattern = string.Format("{0}.jpeg", name);
if (Regex.IsMatch(eachfile, pattern))
{
Attachment oAttachment = await oMail.AddAttachmentAsync(eachfile);
oAttachment.ContentID = name;
}
}
}
}
await oSmtp.SendMailAsync(oServer, oMail);
popUpMsgs.popup(" The Mail has been sent");
}
}
catch (Exception ep)
{
popUpMsgs.popup(String.Format("Failed to send email with the following error: {0}", ep.Message));
}
The built-in e-mail API only support sending plain text e-mail messages as Docs state:
This method only sends plain text messages. You can't set the body of the message to the HTML format.
What you can do is attach images to the e-mail:
EmailMessage mail = new EmailMessage();
mail.Sender = new EmailRecipient("test#example.com");
mail.To.Add(new EmailRecipient("someone#example.com"));
mail.Subject = "Hello";
mail.Body = "World";
var file = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Assets/StoreLogo.png"));
mail.Attachments.Add(new EmailAttachment(file.Name, file));
await Windows.ApplicationModel.Email.EmailManager.ShowComposeNewEmailAsync(mail);
In addition, sending attachments works well only in case of the built-in UWP Outlook Mail client. Classic Outlook will most likely ignore the attachments altogether.
If you need to embed the image, you will need to use a e-mail service. I can recommend SendGrid or MailGun. Both have C# APIs which work like a breeze. They are also free for limited number of e-mails.
There are several ways you can embed the images in a HTML e-mail message.
The oldest is using CID (Content ID) which you were using in your question.
Second option is using Base64 encoding. You first turn your image into a Base64 string. There are many tutorials on this, for example in this blogpost. Then you can just embed the image in the src of your <img> tag:
<img src="data:image/jpeg;base64, YOURIMAGEINBASE64"/>
Finally you can embed an image which is hosted somewhere. This scales the best if you need to send the e-mail to many recipients, but of course requires actually hosting the image somewhere. Of the three methods it is also supported in most clients.
All three approaches are described in detail in this post.
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/
I`m trying to send e-mail via c# and use the following code:
public static bool SendSMTPMail(string smtphost, int smtpport, string smtplogin, string smtppassword, string from, string to, string subject, string body, bool isHtml)
{
try
{
using (MailMessage message = new MailMessage(from, to, subject, body))
{
message.IsBodyHtml = isHtml;
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.BodyEncoding = System.Text.Encoding.UTF8;
SmtpClient mailClient = new SmtpClient(smtphost, smtpport);
mailClient.EnableSsl = false;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.Credentials = new NetworkCredential(smtplogin, smtppassword);
mailClient.Send(message);
return true;
}
}
catch
{
return false;
}
}
It works fine, when mails recieved in Windows, but when user trying to read them in MacOS - subject header is in wrong encoding.
If I set subject encoding to Windows-1251, it works good, but only for cyrillic subjects, and I`m going to send asian too...
How can I send emails using pure Unicode?
And the second question - if I`ll add any attachment to the mail, it will be added with extra files - "filelist.xml" and "header.htm".
How to get rid of them?
Thaks!
The better solution is to create a structure or an automation that impse to system different encodings following the receiver format:
generic utf8
iso xxx for cyrillic
iso xxy for chinese
and so on.
About my second question found this, and it`s helps
For encoding issues I choose to send mails with subjects in english only...