I am trying to attach the mail template in Mail Kit I am using .NET Core
here is my code
//From Address
string FromAddress = "info#gorollo.com";
string FromAdressTitle = "Gorollo";
//To Address
string ToAddress = email;
string Subject = subject;
string BodyContent = message;
var body = new BodyBuilder();
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress
(FromAdressTitle,
FromAddress
));
mimeMessage.To.Add(new MailboxAddress
(
ToAddress
));
mimeMessage.Subject = Subject;
using (var client = new SmtpClient())
{
client.Connect("smtp.mailgun.org", 587, false);
client.Authenticate(
"info#gorollo.com",
"password"
);
await client.SendAsync(mimeMessage);
await client.DisconnectAsync(true);
}
i saw many examples but not able to find the exact solution
so please anyone help me to sort out the problem
I have to attach Signup template in my mail here.
You're almost here. You can use the BodyBuilder to add text or HTML to the body. Either use the TextBody or HtmlBody property to set text or HTML respectively. Use the ToMessageBody() method to create a MimeEntity instance which you can use as the mail body.
Example:
var message = new MimeMessage();
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "<h1>Hello, World!</h1>";
message.Body = bodyBuilder.ToMessageBody();
Related
I am trying to send email using C# but I am getting below error.
Mailbox was unavailable. The server response was: Relay access denied. Please authenticate.
I am not sure why I am getting this error. Here, I am using smtp2go third party to send this email.
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#wraptite.com");
mail.To.Add("test1#gmail.com");
mail.Subject = "Test Email";
mail.Body = "Report";
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password");
//SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
I've tried your code and it work fine.
But in my case, to use the smtp server, from(email address of sender) must use the same domain to authenticate.(but gmail is available to this Send emails from a different address or alias)
So, If your SMTP server connect to smtp2go.com, try as below.
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#smtp2go.com");
Or if you need to use service of smtp2go, it would be better use rest API.
Here is updated by your comment when using gmail.
Gmail required secure app access. that's a reason why code is not work.
So, there is two options for this.
1. Update your gmail account security
(origin idea from here : C# - 이메일 발송방법)
Go to here and turn on "Less secure app access". after doing this your code will work.(it works)
2. Using "Google API Client Library for .NET."
I think this is not so easy, check this out, I found an answer related with this here
#region SendMail
//Mail Setting
string EmailSubject = "EmailSubject";
string EmailBody = "EmailBody";
try
{
string FromAddress = "abc#gmail.com";
string EmailList = "abc1#gmail.com";
string EmailServer = "ipofemailserver";
using (var theMessage = new MailMessage(FromAddress, EmailList))
{
// Construct the alternate body as HTML.
string body = "EmailBody";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
theMessage.AlternateViews.Add(alternate);
theMessage.Subject = EmailSubject;
theMessage.IsBodyHtml = true;
SmtpClient theSmtpServer = new SmtpClient();
theSmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
theSmtpServer.Host = EmailServer;
theSmtpServer.Send(theMessage);
}
}
catch (Exception ex)
{
string AppPath = AppDomain.CurrentDomain.BaseDirectory;
string ErrorPath = AppDomain.CurrentDomain.BaseDirectory + "File\\Error\\";
string OutFileTime = DateTime.Now.ToString("yyyyMMdd");
using (StreamWriter sw = new StreamWriter(ErrorPath + OutFileTime + ".txt", true, System.Text.Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + ":");
sw.WriteLine(ex.ToString());
sw.Close();
}
}
#endregion
BodyBuilder bodyBuilder = new BodyBuilder();
messageContent.Body = "<b>This is a test mail</b>";
bodyBuilder.HtmlBody = messageContent.Body;
I tried to embed my body to a bodybuilder but when I received the email, it returned an empty body. I have an exception that would throw an argument if the body is empty..
Using a BodyBuilder like you are doing is probably the easiest way.
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "<b>This is some html text</b>";
bodyBuilder.TextBody = "This is some plain text";
message.Body = bodyBuilder.ToMessageBody();
client.Send(message);
MimeKit Documentation - Creating Messages
var message = new MimeMessage();
message.Body = new TextPart ("html") { Text = "<b>Test Message</b>" };
"A TextPart is a leaf-node MIME part with a text media-type. The first argument to the TextPart constructor specifies the media-subtype: plain, html, enriched, rtf, and xml."
One other option here if you want to be strict;
msg.Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = "<b>html content</b>" };
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = body;
bodyBuilder.TextBody = "-";
message.Body = bodyBuilder.ToMessageBody();
In some mail ISP, you should always set bodyBuilder.TextBody by value.
I've got this working code to send an email using my gmail account:
public static void SendEmail(string fullName, string toEmail, string HH, string HHEmailAddr)
{
var fromAddress = new MailAddress(FROM_EMAIL, FROM_EMAIL_NAME);
var toAddress = new MailAddress(toEmail, fullName);
var toAddressHH = new MailAddress(HHEmailAddr, HH);
string fromPassword = GMAIL_PASSWORD;
List<String> htmlBody = new List<string>
{
"<html><body>",
. . .
"</body></html>"
};
var body = string.Join("", htmlBody.ToArray());
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
smtp.Send(message);
}
}
The problem is that I want to send the email to two recipients, not one. I can theoretically add another message to the end of that code like so:
. . .
using (var messageHH = new MailMessage(fromAddress, toAddressHH)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
smtp.Send(messageHH);
}
}
...sending two emails from one code block, but what I really want to do is something like this:
List<MailAddress> recipients = new List<MailAddress>();
recipients.Add(toAddress);
recipients.Add(toAddressHH);
. . .
using (var message = new MailMessage(fromAddress, recipients)
...but there seems to no such overload for MailMessage's constructor. How can I add a second recipient to the sending of an email from gmail? Both as a co-recipient and as a "CC" recipient would be nice to know.
UPDATE
If I do try the suggested:
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
To.Add("dplatypus#att.net", "Duckbilled Platypus")
})
...I get:
Invalid initializer member declarator
..and:
The name 'To' does not exist in the current context
I get the same with the following permutation:
To.Add(new MailAddress("dplatypus#att.net", "Duckbilled Platypus"))
Looking at Microsoft's Documentation, you can see that the MailMessage.To property is a MailAddressCollection.
The MailAddressCollection has an Add() method that will append values to the collection.
With that information, you can try something like this:
messageHH.To.Add(new MailAddress("recipient1#domain.com","Recipient1 Name"));
messageHH.To.Add(new MailAddress("recipient2#domain.com","Recipient2 Name"));
messageHH.To.Add(new MailAddress("recipient3#domain.com","Recipient3 Name"));
//etc...
I had to change the "style" of declaration, but this works:
var message = new MailMessage(fromAddress, toAddress);
message.Subject = subject;
message.Body = body;
message.To.Add(new MailAddress("dplatypus#att.net", "Duckbilled Platypus"));
message.To.Add(new MailAddress("duckbill#att.net", "Platypus 2"));
smtp.Send(message);
Could anyone tell me why the following code is sending out emails in raw Html? As in, the email looks like when you view a page source.
I have cut down the code so as not to include attachments and from addresses.
If I disable the line with the alternate view the email renders correctly but I also want to send out a plain text version.
using (SmtpClient client = GetSmtpClient(settings)) {
using (MailMessage message = new MailMessage()) {
message.IsBodyHtml = true;
message.BodyEncoding = System.Text.Encoding.GetEncoding("iso-8859-1");
message.To.Add(toList);
message.Subject = subject;
message.Body = htmlTemplate;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(textTemplate, new ContentType("text/plain")));
client.Send(message);
}
}
Edit: The message was originally sending text as the main body and html as the alternative view but I have run into a problem with accented and foreign characters as described here and wanted to set IsBodyHtml to true, which forces me to set html to the main view.
I had problems with this also but here's a very much cutdown version of code that worked for me...
private MailMessage CreateEmailMessage(string emailAddress) {
MailMessage msg = new MailMessage();
msg.From = new MailAddress(FromEmailAddress, FromName);
msg.To.Add(new MailAddress(emailAddress));
msg.Subject = "Msg Subject here";
string textBody = File.ReadAllText(TextTemplateFile);
string htmlBody = "";
if (EmailFormat == "html") {
htmlBody = File.ReadAllText(HtmlTemplateFile);
foreach (Attachment inline in InlineAttachments) {
inline.ContentDisposition.Inline = true;
msg.Attachments.Add(inline);
}
AlternateView alternateHtml = AlternateView.CreateAlternateViewFromString(htmlBody,
new ContentType("text/html"));
msg.AlternateViews.Add(alternateHtml);
AlternateView alternateText = AlternateView.CreateAlternateViewFromString(textBody,
new ContentType("text/plain"));
msg.AlternateViews.Add(alternateText);
}
else {
msg.Body = textBody;
}
return msg;
}
In the end I realised that the 'htmlTemplate' string being passed into the method was defining charset=ISO-8859-1 in the head of the email and therefore overriding any changes I was making in the code.
I changed the charset to UTF-8, and restored my code to this:
using (SmtpClient client = GetSmtpClient(settings)) {
using (MailMessage message = new MailMessage()) {
message.To.Add(toList);
message.Subject = subject;
message.Body = textTemplate;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(htmlTemplate, new ContentType("text/html")));
client.Send(message);
}
}
and can now send both text and html templates as well as cover the accented characters problem.
I'm using the following code from this answer Sending email in .NET through Gmail. The trouble I'm having is adding an attachment to the email. How would I add an attachment using the code below?
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
The message object created from your new MailMessage method call has a property .Attachments.
For example:
message.Attachments.Add(new Attachment(PathToAttachment));
Using the Attachment class as proposed in the MSDN:
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
Correct your code like this
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);
http://csharp.net-informations.com/communications/csharp-email-attachment.htm
hope this will help you.
ricky
Hint: mail body is overwritten by attachment file path if attachment is added after, so attach first and add body later
mail.Attachments.Add(new Attachment(file));
mail.Body = "body";
A one line answer:
mail.Attachments.Add(new System.Net.Mail.Attachment("pathToAttachment"));