I am not able to send email from a xamarin.android app using MailKit library of jstedfast.
I am using the following code :
try
{
//From Address
string FromAddress = "from_sender#gmail.com";
string FromAdressTitle = "Email Title";
//To Address
string ToAddress = "to_receiver#gmail.com";
string ToAdressTitle = "Address Title";
string Subject = "Subject of mail";
string BodyContent = "Body of email";
//Smtp Server
string SmtpServer = "smtp.gmail.com";
//Smtp Port Number
int SmtpPortNumber = 587;
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
mimeMessage.Subject = Subject;
mimeMessage.Body = new TextPart("plain")
{
Text = BodyContent
};
using (var client = new SmtpClient())
{
client.Connect(SmtpServer, SmtpPortNumber, false);
// Note: only needed if the SMTP server requires authentication
// Error 5.5.1 Authentication
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate("from_sender#gmail.com", "password");
client.Send(mimeMessage);
Console.WriteLine("The mail has been sent successfully !!");
Console.ReadLine();
client.Disconnect(true);
}
}
catch (Exception ex)
{
string message = ex.Message;
}
When I run this code from my app, it throws an exception:
MailKit.Security.AuthenticationException
What I am missing in this code. Can anybody help me out !
Use MAILMESSAGE class.
using System.Net.Mail;
.
MailMessage mail = new MailMessage("example#gmail.com", "example#gmail.com", "Title","Body");
SmtpClient client = new SmtpClient();
client.Host = ("smtp.gmail.com");
client.Port = 587; //smtp port for SSL
client.Credentials = new System.Net.NetworkCredential("example#gmail.com", "password");
client.EnableSsl = true; //for gmail SSL must be true
client.Send(mail);
I have created a Windows application which is used to send emails. i have given credentials. i turned on google/settings/lesssecure apps. Eventhough its not sending. Its showing the error The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required here is my code.
MailMessage message = new MailMessage();
message.From = new MailAddress("Selvacsebe23#gmail.com");
string[] mailaddress = new string[count];
int i;
if (textSubject.Text != string.Empty)
{
message.Subject = textSubject.Text;
if (textBody.Text != string.Empty)
{
message.To="Selvakesavan#gmail.com"
message.IsBodyHtml = true;
string tmpBody = "Hello " + "," + "<br/> <br/>" + textBody.Text + "<br/> <br/>" + "Thanks and Regardds";
message.Body = tmpBody;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("selvacsebe23#gmail.com", "mypassword");
message.Priority = MailPriority.High;
client.EnableSsl = true;
client.Send(message);
MessageBox.Show("Mail has sent successfully !!!", "Success !");
}
else
{
MessageBox.Show("Please Enter Body of the Message !");
}
}
else
{
MessageBox.Show("Please Enter Subject !");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Failure !");
log.Fatal(ex.Message);
}
}
If you turn on 2-step-verification, then you need to login using app-specific-password. You can create it here:
https://support.google.com/accounts/answer/185833?hl=en. If you use your normal password, then you will get exception : 5.5.1 Authentication Required. You don't need lots of code, this code is enough to send email without attachment:
const string from = "user1#gmail.com";
const string to = "user2#yahoo.com";
const string subject = "This is subject";
const string body = "This is body";
const string appSpecificPassword = "akdfkajsdhklakdfh";
var mailMessage = new MailMessage(from, to, subject, body);
using (var smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.EnableSsl = true;
smtpClient.Credentials = new NetworkCredential(from, appSpecificPassword);
smtpClient.Send(mailMessage);
}
I tried to send mail from my asp.net web application.
I want to send my application password to the user mail id, for that I took the password from datatabase using getdetailss function.
btn4getPwd is the button calling the mailing function.
txtusername.Text is the text box containing sending mail address. All values are receiving correctly, no error occur but it's not working ..!
protected void btn4getPwd_Click(object sender, EventArgs e)
{
if (txtusername.Text.Trim() != "")
{
em.username = txtusername.Text.Trim();
DataTable forget = em.getdetailss(10);
string passwd = (forget.Rows[0]["PassCode"].ToString());
try
{
string Subject = "Your NLS Password";
string Body = passwd;
string ToEmail = txtusername.Text.Trim();
string SMTPUser = "mymail#gmail.com", SMTPPassword = "pswd";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(SMTPUser, "AspnetO");
mail.To.Add(ToEmail);
mail.Body = Body;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.Normal;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPassword);
smtp.EnableSsl = true;
smtp.Send(mail);
Response.Write("<script language=javascript>alert('Mail send...!! ')</script>");
}
catch (SmtpException ex)
{
lbl4get.Text = "SmtpException ";
}
catch (Exception ex)
{
lbl4get.Text = "Exception";
}
}
else { Response.Write("<script language=javascript>alert('Invalid USERNAME...!! ')</script>"); }
}
smtp.Port = 25; is default port but for as you are sending over SSL use port 587 or 465 (nonstandard, but sometimes used for legacy reasons). Assume NetworkCredential are correct.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending email in .NET through Gmail
This mail code is working in localhost i.e on my computer but when i uopload it on server it is not working.
The error is : Failure sending mail. please tell me where is the problem.
if (Session["userinfo"] != null)
{
lblTest.Text = Session["userinfo"].ToString();
MailMessage msg = new MailMessage();
msg.From = new MailAddress("shop.bcharya#gmail.com");
msg.To.Add(new MailAddress("bcc#dr.com"));
msg.To.Add(new MailAddress("info#yzentech.com"));
msg.Subject = "Mail from BcharyaCorporation.online shopping site";
msg.Body = ""+lblTest.Text+" wants to buy some products. please contact with him/her";
SmtpClient sc = new SmtpClient();
sc.Host = "smtp.gmail.com";
// sc.Port = 25;
sc.Credentials = new NetworkCredential("shop.bcharya#gmail.com", "mypassword");
sc.EnableSsl = true;
try
{
sc.Send(msg);
lblPayment.Text = "Sorry. Currently we are out of online payment service. We will contact you for payment process. Thank you for buying this product.";
}
catch (Exception ex)
{
lblPayment.Text=ex.Message.ToString();
Response.Write(ex.Message);
}
}
For gmail mail settings add Port number too
sc.Port = 587;
after this line
sc.Host = "smtp.gmail.com";
Only use port 587 and SSL if the SMTP server supports that (GMail and Hotmail for example). Some servers just use port 25 and no SSL.
Use below method and then check :
SmtpClient sc = new SmtpClient(string); //sends e-mail by using the specified SMTP server
You can use this below given code for sending email. Here sending the error details through email is one method. Try this code for sending email.
using System.Web.Mail
public static bool SendErrorEmail(string to, string cc, string bcc, string subject, string body, MailPriority priority, bool isHtml)
{
try
{
using (SmtpClient smtpClient = new SmtpClient())
{
using (MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress(“yourmail#domain.com”, “Your name”);
// You can specify the host name or ipaddress of your server
smtpClient.Host = “mail.yourdomain.com”; //you can specify mail server IP address here
//Default port is 25
smtpClient.Port = 25;
NetworkCredential info = new NetworkCredential(“yourmail#domain.com”, “your password”);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = info;
//From address will be given as a MailAddress Object
message.From = from;
message.Priority = priority;
// To address collection of MailAddress
message.To.Add(to);
message.Subject = subject;
// CC and BCC optional
if (cc.Length > 0)
{
message.CC.Add(cc);
}
if (bcc.Length > 0)
{
message.Bcc.Add(bcc);
}
//Body can be Html or text format;Specify true if it is html message
message.IsBodyHtml = isHtml;
// Message body content
message.Body = body;
// Send SMTP mail
smtpClient.Send(message);
}
}
return true;
}
catch (Exception ee)
{
Logger.LogError(ee, “Error while sending email to ” + toAddress);
throw;
}
}
I have a C# application which emails out Excel spreadsheet reports via an Exchange 2007 server using SMTP. These arrive fine for Outlook users, but for Thunderbird and Blackberry users the attachments have been renamed as "Part 1.2".
I found this article which describes the problem, but doesn't seem to give me a workaround. I don't have control of the Exchange server so can't make changes there. Is there anything I can do on the C# end? I have tried using short filenames and HTML encoding for the body but neither made a difference.
My mail sending code is simply this:
public static void SendMail(string recipient, string subject, string body, string attachmentFilename)
{
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential = new NetworkCredential(MailConst.Username, MailConst.Password);
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(MailConst.Username);
// setup up the host, increase the timeout to 5 minutes
smtpClient.Host = MailConst.SmtpServer;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
smtpClient.Timeout = (60 * 5 * 1000);
message.From = fromAddress;
message.Subject = subject;
message.IsBodyHtml = false;
message.Body = body;
message.To.Add(recipient);
if (attachmentFilename != null)
message.Attachments.Add(new Attachment(attachmentFilename));
smtpClient.Send(message);
}
Thanks for any help.
Simple code to send email with attachement.
source: http://www.coding-issues.com/2012/11/sending-email-with-attachments-from-c.html
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail#gmail.com");
mail.To.Add("to_mail#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Explicitly filling in the ContentDisposition fields did the trick.
if (attachmentFilename != null)
{
Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachmentFilename);
disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
disposition.FileName = Path.GetFileName(attachmentFilename);
disposition.Size = new FileInfo(attachmentFilename).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
Here is a simple mail sending code with attachment
try
{
SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
string from = "myemail#gmail.com";
string to = "reciever#gmail.com";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Enter the subject here";
msg.Body = "The message goes here.";
msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email. Error : " + ex);
}
Read more Sending emails with attachment in C#
Completing the solution of Ranadheer, using Server.MapPath to locate the file
System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);
private void btnSent_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(txtAcc.Text);
mail.To.Add(txtToAdd.Text);
mail.Subject = txtSub.Text;
mail.Body = txtContent.Text;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(txtAttachment.Text);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
openFileDialog1.ShowDialog();
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName);
mail.Attachments.Add(attachment);
txtAttachment.Text =Convert.ToString (openFileDialog1.FileName);
}
I've made a short code to do that and I want to share it with you.
Here the main code:
public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(from);
email.To.Add(to);
email.Subject = subject;
email.Body = Message;
SmtpClient smtp = new SmtpClient(host, port);
smtp.UseDefaultCredentials = false;
NetworkCredential nc = new NetworkCredential(from, password);
smtp.Credentials = nc;
smtp.EnableSsl = true;
email.IsBodyHtml = true;
email.Priority = MailPriority.Normal;
email.BodyEncoding = Encoding.UTF8;
if (file.Length > 0)
{
Attachment attachment;
attachment = new Attachment(file);
email.Attachments.Add(attachment);
}
// smtp.Send(email);
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
string userstate = "sending ...";
smtp.SendAsync(email, userstate);
}
private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
string result = "";
if (e.Cancelled)
{
MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else if (e.Error != null)
{
MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example
using (OpenFileDialog attachement = new OpenFileDialog()
{
Filter = "Exel Client|*.png",
ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
Send("yourmail#gmail.com", "gmail_password",
"tomail#gmail.com", "just smile ", "mail with attachement",
"smtp.gmail.com", 587, attachement.FileName);
}
}
Try this:
private void btnAtt_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
Attachment myFile = new Attachment(openFileDialog1.FileName);
MyMsg.Attachments.Add(myFile);
}
I tried the code provided by Ranadheer Reddy (above) and it worked great. If you’re using a company computer that has a restricted server you may need to change the SMTP port to 25 and leave your username and password blank since they will auto fill by your admin.
Originally, I tried using EASendMail from the nugent package manager, only to realize that it’s a pay for version with 30-day trial. Don’t waist your time with it unless you plan on buying it. I noticed the program ran much faster using EASendMail, but for me, free trumped fast.
Just my 2 cents worth.
Use this method it under your email service it can attach any email body and attachments to Microsoft outlook
using Outlook = Microsoft.Office.Interop.Outlook; // Reference Microsoft.Office.Interop.Outlook from local or nuget if you will user a build agent later
try {
var officeType = Type.GetTypeFromProgID("Outlook.Application");
if(officeType == null) {//outlook is not installed
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
} else {
// Outlook is installed.
// Continue your work.
Outlook.Application objApp = new Outlook.Application();
Outlook.MailItem mail = null;
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
//The CreateItem method returns an object which has to be typecast to MailItem
//before using it.
mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
//The parameters are explained below
mail.To = recipientEmailAddress;
//mail.CC = "con#def.com";//All the mail lists have to be separated by the ';'
//To send email:
//mail.Send();
//To show email window
await Task.Run(() => mail.Display());
}
} catch(System.Exception) {
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
}