What Address should I give in From field in SendEmail using c# - c#

I caught into big problem since am new to SMTP Email Server.
I have installed smtp server in my web server and configured the required details. My emails are now sending but in spam
I have implemented SendMail code using c# in my webapplication and I have one clarification on that.
string mailFrom = "Newsletter#my-domain.com";
string message = string.Empty;
System.Net.Mail.MailMessage email = new MailMessage(mailFrom, EmailAddress);
email.Subject = "Mail from my-domain.com";
email.Body = message;
email.IsBodyHtml = true;
email.Priority = MailPriority.High;
System.Net.Mail.SmtpClient mailClient = new SmtpClient();
System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("username", "password");
mailClient.Host = "my-mail-server-domain.com";
mailClient.Port = 25;
mailClient.EnableSsl = false;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicAuthenticationInfo;
try
{
mailClient.Send(email);
}
catch (Exception ex)
{
log4net.ILog logger = log4net.LogManager.GetLogger("File");
logger.Error(ex.ToString());
}
What value should I give for mailFrom. Is valid email is required for From address? Does it cause sending mail as spam? I don't have emailid in the name of newsletter#my-domain.com. What shall I do for that?
Please anyone clarify on this.

It is the responsibility of the mail server the validation of the address, all could be good or bad for c#. I think your focus is wrong.

The from should be a valid email address. That is the email from where an email is sent. The network credentials that you specify must match with the from address. Once you provide a valid email address, the emails will not go to spam folder hopefully.

Related

How to send email from a C# program

I would like to add email functionality to a WinForm program I'm writing in C#. I have an Android app that has email functionality. What it does is set up the email but then lets the user choose the email program, etc. Once that is chosen the email body is completed. But it's up to the use to select what email app they want to use.
I would like to do the same in Windows but I don't see how. I have tried the following (based on other questions and responses here) :
_from = new MailAddress("my email address", "xxxx");
_to = new MailAddress("xxxx3333#gmail.com", "yyyy");
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.UseDefaultCredentials = true;
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp msgMail = new MailMessage();
smtp.Body = text;
msgMail.Subject = "Subject";
msgMail.From = _from;
msgMail.To.Add(_to);
smtp.EnableSsl = true;
msgMail.Subject = _subject;
msgMail.Body = Text;
msgMail.IsBodyHtml = false;
try
{
mailClient.Send(msgMail);
}
catch (Exception ex)
{
string msg = "Exception caught in sending the email: " + ex.ToString();
showMessage(msg);
}
msgMail.Dispose();
But I get:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
With similar code in Android, my program just gets to an email form but lets the user decide what email add they will use.
Is there a way to do this in Windows?
There is an almost identical question and response here:
C# Windows Form Application - Send email using gmail smtp
And I think I've followed this but...doesn't work.
To directly answer your question - you probably haven't enabled less secure apps on the gmail account you are using.
Otherwise though, you could investigate the syntax of mailto if you want to let the user elect a mail client to use to send the email: https://www.labnol.org/internet/email/learn-mailto-syntax/6748/
From the link:
Send an email to Barack Obama with the subject “Congrats Obama” and some text in the body of the email message
<a href=”mailto:obama#whitehouse.gov?
subject=Congrats%20Obama&body=Enjoy%20your%20stay%0ARegards%20″>
This isn't directly related to C#/Windows - but I do know entering mailto:someone#somewhere.com at the Run prompt works:
Presumably then you could do something like: (untested)
Process.Run("mailto:someone#somewhere.com");
From the server response messages it looks like you have to provide login credentials before you are allowed to send.
Replace:
smtp.UseDefaultCredentials = true;
With:
smtp.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
This should do the trick.
You may have forgotten in your code to add the Host
Try to use this :
SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = true;
smtp.Host = "SRVMAIL";

send an email using SMTP without password in C#

I have a web application using ASP.net and C#,in one step it will need
from the user to
send an email to someone with an attachments.
my problem is when the user will send the email i don't want to put their
password every time the user send.
i want to send an email without the password of the sender.
any way to do that using SMTP ?
and this is a sample of my code "not all".
the code is worked correctly when i put my password , but without it ,it
is not work, i need a way to send emails without put the password but
in the same time using smtp protocol.
private void button1_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.office365.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "my email";
string password = "******";
string emailTo = "receiver mail";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
// mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
// mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));
using (SmtpClient smtp = new SmtpClient(smtpAddress,portNumber))
{
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
MessageBox.Show("message sent");
}
}
I believe this can be accomplished easily, but with some restrictions.
Have a look at the MSDN article on configuring SMTP in your config file.
If your SMTP server allows it, your email object's from address may not need to be the same as the credentials used to connect to the SMTP server.
So, set the from address of your email object as you already are:
mail.From = new MailAddress(emailFrom);
But, configure your smtp connection one of two ways:
Set your app to run under an account that has permission to access the SMTP server
Include credentials for the SMTP server in your config, like this.
Then, just do something like this:
using (SmtpClient smtp = new SmtpClient())
{
smtp.Send(mail);
}
Let the configuration file handle setting up SMTP for you. This is also great because you don't need to change any of your code if you switch servers.
Just remember to be careful with any sensitive settings in your config file! (AKA, don't check them into a public github repo)

using gmail as smpt for deliver email from mvc controller

I'm trying to send email from asp.net mvc controller. Gmail account used here for smpt is configured to use with less security, so that's not the problem here.
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
I'm using code
var text = "email body to deliver";
SendEmail("mydeliverEmailAddress#gmail.com", text);
public static bool SendEmail(string SentTo, string Text)
{
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("myemail#gmail.com", "myGmailPass");
client.Port = 465;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
MailAddress
maFrom = new MailAddress("sender_email#domain.tld", "Sender's Name", Encoding.UTF8),
maTo = new MailAddress(SentTo, "Recipient's Name", Encoding.UTF8);
MailMessage mmsg = new MailMessage(maFrom.Address, maTo.Address);
mmsg.Body = "<html><body><h1>Some HTML Text for Test as BODY</h1></body></html>";
mmsg.IsBodyHtml = true;
mmsg.Subject = "Some Other Text as Subject";
mmsg.SubjectEncoding = Encoding.UTF8;
client.Send(mmsg);
}
catch (Exception ex)
{
}
return true;
}
Wait a minute. You are using your gmail account: myemail#gmail.com and trying to send an email on behalf of sender_email#domain.tld?
For more than obvious reasons that's never gonna work. So make sure that you are using the same email address as the one you are authenticating against:
maFrom = new MailAddress("myemail#gmail.com", "Sender's Name", Encoding.UTF8),
You can only send emails from the account you are authenticated against. Of course the recipient email can be any address that gmail can deliver to.
You've got another issue with your code. You are using a wring port here:
client.Port = 465;
The correct port that gmail SMTP works with is the following:
client.Port = 587;
Also you might want to ensure that you have enabled less secure apps in your gmail account or you will not be able to use SmtpClient in .NET to send emails using this SMTP: https://www.google.com/settings/security/lesssecureapps?pli=1
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
What error message do you expect to get when you did the worst ever possible thing? You wrapped your code in a try/catch block and in your catch block you did absolutely nothing. You just consumed the exception:
catch (Exception ex)
{
}
So make sure that you do something useful with an exception if you are going to be catching it. For example something useful could be to log this exception and send an error message to the user saying that something bad happened and you couldn't send an email and that you are investigating the issue right now.
var smtpClient = new SmtpClient("YourSMTPServer", "SMTPServerPort"))
{
Credentials = new NetworkCredential("YourEmail",
"Password"),
EnableSsl = false
};
string fromEmail = "YourEmail";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmail);
mailMessage.To.Add("Recipient's EMail");
mailMessage.Subject = "Test Mail";
mailMessage.Body = "This is test Mail";
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);

How do I send an email with Gmail and SmtpClient when the sending account uses two factor authentication?

SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential =
new NetworkCredential("sender#gmail.com", "password");
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("sender#gmail.com");
smtpClient.EnableSsl = true;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
//Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>Hello, this is a demo ... ..</h1>";
message.To.Add("receiver#gmail.com");
try
{
smtpClient.Send(message);
}
catch (Exception ex)
{
//Error, could not send the message
ex.ToString();
}
// The thing is that this code works fine for gmails without phone number protection. Exception occurs when using this code with gmails that are protected(verified) via the client phone number.
One of the solution is to use a remote server to access clients mails.
Now my question is there another method to solve this issue ? other than third parties.
If I understand you correctly, you're saying the Google account is using two-factor authentication.
If that's the case, you need to create an Application Password for this. Go to https://security.google.com/settings/security/apppasswords once logged in as the account you want to two-factor auth with.
In the list, under Select App choose "Other" and give it some name. Click Generate, and write this password DOWN cause you will only ever see it ONCE. You will use this in your authentication. It will be 16-characters long and the spaces don't matter, you can include them or omit them. I included them here just because.
NetworkCredential basicCredential =
new NetworkCredential("sender#gmail.com", "cadf afal rqcf cafo");
MailMessage message = new MailMessage();

How to send HTML email with Image using asp.net with c#

Hi all of you I try following code to send HTML email along with Image in HTML
but I can receive only text format mail not Image
public void HTML_mail(string mailTo,string mailSub,string mailMessage)
{
try
{
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
//client.Host = "smtp.gmail.com";
//client.Port = 587;
//WITH SMTP Server with Authenticaton
client.Host = mailServer;
client.Port = Convert.ToInt16(serverPort);
// setup Smtp authentication
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(userName, passWord);
client.UseDefaultCredentials = false;
client.Credentials = credentials;
MailMessage msg = new MailMessage();
msg.From = new MailAddress(userName);
msg.To.Add(new MailAddress(mailTo));
msg.Subject = mailSub;
msg.IsBodyHtml = true;
msg.Body = string.Format(mailMessage);
//HTML CODE "<html><head></head><body><p><h3>Dadu</h3></p><img src='http://localhost:2727/photo/mukeshwedsjashmin/1/Suresh2.jpg' height='500px' width='500px' alt='' /></body>"
try
{
client.Send(msg);
//lblMsg.Text = "Your message has been successfully sent.";
}
catch (Exception ex)
{
//lblMsg.ForeColor = Color.Red;
//lblMsg.Text = "Error occured while sending your message." + ex.Message;
}
}
catch(Exception ex)
{
}
}
I can Only see the "Dadu" in the mail
I choose display Image on my gmail A/C
You're email is referencing a localhost image, try it wih an online one as the image may not be available to the email.
Your email is referencing a local image:
http://localhost:2727/photo/mukeshwedsjashmin/1/Suresh2.jpg
The only e-mail receiver that will be able to see that image is yourself. No one else will have access to your local web server, thus won't be able to see the image.
You need to reference an image that is available to the public.
As a side note
In my experience, sending emails like this from a local mail server, especially if the email contain HTML and images, will almost certainly be caught as spam. I prefer to send my emails through an email delivery service. I only have experience with Postmark, which has a good .Net library, but I bet there are other great services as well.

Categories

Resources