Strings not compatible for email address - c#

I am new to C#. In my verge of learning this language, I made a windows form application application that takes in an email address and a password and sends it to a pre-specified email address. I don't think that I have messed up the data types though I am getting an error The specified string is not in the form required for an e-mail address.
My code is below :
namespace mailTest
{
public partial class Form1 : Form
{
string mailAddress = "lancepreston#gmail.com";
string mailPassword = "123456789";
string SMTP = "smtp.gmail.com";
public Form1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage(Email.Text, Password.Text); \\ I get the error on this line
SmtpClient client = new SmtpClient(SMTP);
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential(mailAddress,mailPassword);
client.EnableSsl = true;
client.Send(mail);
MessageBox.Show("Mail Sent!", "Success", MessageBoxButtons.OK);
}
}
}
Screenshot of my form :

MailMessage constructor is defined as below
public MailMessage(string from, string to);
First parameter is from address and second is to address, but you seem to pass password in second parameter. That's why you get the exception.

That particular constructor of the MailMessage class expects the first parameter to be the email address of the sender, and the second parameter to be the email address of the recipient:
http://msdn.microsoft.com/en-us/library/14k9fb7t(v=vs.110).aspx
You are providing a password to the parameter that expects the recipient's email address.
I presume you really want to pass the password in the body of the message.
Take a look at the constructor that populates the body, or set the Body property after initializing a MailMessage:
http://msdn.microsoft.com/en-us/library/5k0ddab0(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.body(v=vs.110).aspx

You have to specify UserName in NetworkCredential , like the following:
NetworkCredential myCredentials = new NetworkCredential("","","");
myCredentials.Domain = domain;
myCredentials.UserName = username;
myCredentials.Password = passwd;
See the explanation at:
http://msdn.microsoft.com/en-us/library/system.net.networkcredential.username%28v=vs.110%29.aspx
Also, your MailMessage has wrong parameters (shoud be from/to).
Regards,

Related

Change sender name doesn't work

First of all, I search for an hour how to solve my problem on other posts but the other solutions don't work in my case.
My problem
I need to send a report mail after the execution of my program. To send mails I use System.Net.Mail namespace and particularly SmtpClient class.
The mail is correctly sent but I need to hide the sender mail address.
I tried some different things but none of them seems to work.
What I tried
Firstly I tried to do this :
public static void sendMail(String Titre,String Message)
{
SmtpClient client = new SmtpClient(GestionParametres.getParametre("SMTP"), Int32.Parse(GestionParametres.getParametre("PortSmtp")));
client.Credentials = new System.Net.NetworkCredential(GestionParametres.getParametre("UsernameSmtp"), GestionParametres.getParametre("PasswordSmtp"));
MailAddress from = new MailAddress(GestionParametres.getParametre("ExpediteurMail"),"Rapport interface ****");
MailAddress to = new MailAddress(GestionParametres.getParametre("DestinataireMail"));
MailMessage message = new MailMessage(GestionParametres.getParametre("ExpediteurMail"), GestionParametres.getParametre("DestinataireMail"));
message.From = from;
message.Subject = Titre;
message.Body = Message;
message.BodyEncoding = System.Text.Encoding.UTF8;
client.Send(message);
}
But the sender mail address still appear in mail.
Secondly, I tried this :
public static void sendMail(String Titre,String Message)
{
SmtpClient client = new SmtpClient(GestionParametres.getParametre("SMTP"), Int32.Parse(GestionParametres.getParametre("PortSmtp")));
client.Credentials = new System.Net.NetworkCredential(GestionParametres.getParametre("UsernameSmtp"), GestionParametres.getParametre("PasswordSmtp"));
MailAddress from = new MailAddress(GestionParametres.getParametre("ExpediteurMail"));
MailAddress to = new MailAddress(GestionParametres.getParametre("DestinataireMail"));
MailMessage message = new MailMessage("Rapport interface ****" + GestionParametres.getParametre("ExpediteurMail"), GestionParametres.getParametre("DestinataireMail"), Titre, Message);
client.Send(message);
}
But it doesn't work either...
Now I have no idea how to solve this problem.
Any idea ?
Thank you in advance,
Thomas

Problems with sending an email

I am working with C# and I am trying to send an email form a web page. I am trying to populate the from email address from a textbox and the to email address is being hard coded. My code is as follows and the errors I am getting are after the code.
try
{
MailMessage oMsg = new MailMessage();
// TODO: Replace with sender e-mail address. Get from textbox: string SenderEmail = emailbox.text
oMsg.From = emailbox.Text; //Senders email
// TODO: Replace with recipient e-mail address.
oMsg.To = "DummyRecipient#gmail.com"; //Recipient email
oMsg.Subject = subjecttbox.Text; //Subject of email
// SEND IN HTML FORMAT (comment this line to send plain text).
//oMsg.BodyFormat = MailFormat.Html;
// HTML Body (remove HTML tags for plain text).
oMsg.Body = EmailBody; //Body of the email
// ADD AN ATTACHMENT.
// TODO: Replace with path to attachment.
//String sFile = #"C:\temp\Hello.txt";
//MailAttachment oAttch = new MailAttachment(sFile, MailEncoding.Base64);
//oMsg.Attachments.Add(oAttch);
// TODO: Replace with the name of your remote SMTP server.
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
//SmtpMail.SmtpServer = "Smtp.gmail.com"; //Email server name, Gmail = Smtp.gmail.com
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("DummySenderAddress#gmail.com", "DummyPassword");
SmtpServer.EnableSsl = true;
SmtpMail.Send(oMsg);
oMsg = null;
//oAttch = null;
}
catch //(Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
Cannot implicitly convert type 'string' to
'System.Net.Mail.MailAddress' Property or indexer
'System.Net.Mail.MailMessage.To' cannot be assigned to -- it is read
only
Cannot implicitly convert type 'string' to
'System.Net.Mail.MailAddressCollection' The name 'SmtpMail' does not
exist in the current context
The problem is in your line:
oMsg.To = "DummyRecipient#gmail.com"; //Recipient email
Emails can have more than one recipient. Therefore the "To" property of the MailMessage class is a collection. Not a single email address.
Additionally, you need to create a MailAddress object instead of just using a string for the email.
Use the following line instead of the above.
oMsg.To.Add(new MailAddress("DummyRecipient#gmail.com")); //Recipient email
oMsg.From takes a MailAddress object as its input, not a string. Replace it with:
oMsg.From = new MailAddress(emailbox.Text);
oMsg.To takes a MailAddressCollection as its input. Assuming that collection isn't null, you should be able to replace it with:
oMsg.To.Add("DummyRecipient#gmail.com");

How to configure SMTP mail setting

Hi I want to Configure SMTP mail setting and send mail from C#.
i am using a Form and saved SMTP setting onces in a database.
whenever i want to send mail then i am using below function.
private void _MSendMail(string _pToMailId, string _pBody, string _pMailSubject = "Test Mail")
{
string _SMTPHOST = Value Come From Database;
int _SMTPPORT = Value Come From Database;
bool _ENABLESSL = Value Come From Database;
string _MAILID = Value Come From Database;
string _USERNAME = Value Come From Database;
string _PASSWORD = Value Come From Database;
using (var message = new System.Net.Mail.MailMessage())
{
message.To.Add(_pToMailId);
message.Subject = _pMailSubject;
message.From = new System.Net.Mail.MailAddress(_MAILID);
message.Body = _pBody;
using (var smtp = new System.Net.Mail.SmtpClient())
{
smtp.Host = "smtp." + _SMTPHOST + ".com";
smtp.Port = _SMTPPORT;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(_USERNAME, _PASSWORD);
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.EnableSsl = _ENABLESSL;
try
{
smtp.Send(message);
}
catch (Exception e) { }
}
}
}
My Question is: is this function right or do some change in it ??..
I tested it with Gmail it works. I need your suggestion on other mail providers same function will work or any other change is required.
No, it is not correct. For one thing, you cannot assume that all SMTP servers are of the form "smtp.example.com". What about "example.net"? What about "mail.example.com"?
I recommend having your database store the full SMTP host address. Don't do any computation on that value.
There are a number of things that you have to consider:
Dont fetch the smpt parameters from database inside the function.
Pass the parameters to the function. This will helps if you want to
send many emails repeatedly and you don't have to connect to
database each time.
Don't suppress the exception. Log it or throw the exception so that
outer module can handle it.
As said earlier by c45207, store the full SMPT host address in the
database.
The code only sends mail to single person. Instead use
IList _pToMailId and loop it as follows:
foreach (var to in _pToMailId)
{
message .To.Add(to);
}
You can repead this for CC and BCC respectively.

Email id address issue in c# code

I wrote a simple program in C# Winforms for sending an email and my code is mentioned below:-
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public MailMessage rtnMail()
{
string to = txt_To.Text;
string from = txt_From.Text;
string subject = txt_Subject.Text;
string body = txt_Body.Text;
MailMessage message = new MailMessage(from, to, subject, body);
return message;
}
//Button click event
private void btn_Send_Click(object sender, EventArgs e)
{
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("myanotherid#gmail.com", "password");
smtp.EnableSsl = true;
smtp.Timeout = 500000;
smtp.Send(this.rtnMail());
}
}
when i run this code and put all the values in textboxes like (to, from, body, subject) and click the "Send" button i do end up getting an email at an address
mentioned in the Textbox named txt_To ( which is my recipient gmail account id).But whenever i look at which address(email id) i got this email from in Microsoft
Outlook (which i have configued for my gmail recipeint account), it always says that i got this email from the email address mentioned as first argument in the line of
code below,
smtp.Credentials = new System.Net.NetworkCredential("myanotherid#gmail.com", "password");
My question is, am i doing anything wrong because i expect that email address from which im receiving an email( in my outlook gmail) should be the one that i put in
TextBox named txt_From rather than from "myanotherid#gmail.com" address.
Is there a work around or does there exist an alternate to it.
I guess it's gmail's protection to prevent sender spoofing.
You can't login to GMail as yogibear#gmail.com and send an e-mail as barack.obama#whitehouse.gov. GMail's SMTP will rewrite the message's header to properly indicate who has really sent the e-mail.
You should use new mailaddress();
MailAddress from = new MailAddress("someone#something.com", "John Doe");
MailAddress to = new MailAddress("someoneelse#something.com", "Jane Doe");
MailMessage mail = new MailMessage(from, to);
further reading here: http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress.aspx
Your code looks correct. Gmail does not allow you to specify a different 'from address' unless it is one you have proven belongs to you.
Go to Settings > Accounts > 'Send email as' and add an address there. You can only choose to send from any of the accounts you have configured here.

Unable to send email through local SMTP server

I am working with sending email through C# in asp.net, with IIS7.
But I couldn't fix the error.
I cannot even send a message to this path
C:\inetpub\mailroot\Queue
This is the simplest code I have used
MailMessage m = new MailMessage();
m.From = TextBox1.Text;
m.To = TextBox2.Text;
m.Subject = TextBox3.Text;
m.Body = TextBox4.Text;
SmtpMail.SmtpServer = "localhost"; //your real server goes here
SmtpMail.Send(m);
note: that I manually created this path, isn't wrong? or should be created automatically?
Please HELP!
If you manually created the path, then the SMTP Service is not installed on your machine (assuming that you intend to use this and not a third-party SMTP server).
You can verify this by looking in the list of services (I believe it starts with Simple Mail Transport...).
Perhaps it's the SmtpCredentials that's missing? And as the earlier speekers have said that the SmtpServer is it really localhost, meaning that you have a smtpserver on your machine?
I've done a SMTP mail to send som emails from my program that is working, perhaps you can find something in this that can help you?
It looks like this.
public class Email
{
public Email(string recieverAdress)
{
mail = new MailMessage(senderAdress, recieverAdress);
}
private readonly MailMessage mail;
private readonly SmtpClient smtpClient = new SmtpClient("smtp.domain.com", port);
private readonly NetworkCredential credential = new NetworkCredential("username", "password");
public void SendMail(string subject, string textInBody)
{
mail.Subject = DateTime.Now + " " + subject;
mail.Body = textInBody;
smtpClient.Credentials = credential;
smtpClient.Send(mail);
}
}

Categories

Resources