- Home /
How to use variable in MailMessage To?
I'm trying to set the To in a MailMessage from a string variable (forwardEmail) but it doesn't ever send an email or even throw and exception, it shows it was sent successful but it never sends.
public string forwardEmail = "recevierEmail@something.com";
public string fromEmail = "testEmail@something.com";
public string password = "";
public string subject = "Test subject"
public void SendEmail(string body)
{
MailMessage mail = new MailMessage();
mail.IsBodyHtml = true;
mail.From = new MailAddress(fromEmail);
mail.To.Add(forwardEmail); //<-------Doesn't work but mail.To.Add("recevierEmail@something.com") does?
mail.Subject = "Test Smtp Mail";
mail.Body = body;
SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
smtpServer.Port = 587;
smtpServer.Credentials = new System.Net.NetworkCredential(fromEmail, password) as ICredentialsByHost;
smtpServer.EnableSsl = true;
ServicePointManager.ServerCertificateValidationCallback =
delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
try
{
smtpServer.Send(mail);
}
catch (System.Exception)
{
sendingText.text = "Email not sent";
}
finally
{
sendingText.text = "Email was sent!;
}
}
Whats weird is if I set the mail.To.Add()
parameter directly like mail.To.Add("recevierEmail@something.com")
it works fine. I'm not sure why mail.To.Add(forwardEmail)
is not working from a variable because I am setting the mail.From()
mail.Subject()
and mail.Body()
from string variables and they are working fine but only if I directly set the mail.To.Add("recevierEmail@something.com")
directly and not a variable. I have doubled checked the the forwardEmail is correct, double checked and removed white space in the string, the forwardEmail is always correct, I don't know what else to try, any help would be appreciated.
Answer by Bunny83 · Oct 28, 2020 at 02:14 AM
This is very unlikely. I suspect that you edited the address in the inspector. Since your "forwardEmail" variable is public it will be serialized by Unity. So check the inspector what exactly is serialized in that field. The address you assigned in the field initializer is irrelevant.
@Bunny83 I was sure I didn't edit the address in the inspector because the variable initially started off private and I still had the same issue. After some tinkering I figured it out though, after checking the Length of the string, it was always +1 bigger than what was typed in the input, my problem was the variable was being set from an T$$anonymous$$P_InputField, but I was pulling the value from the Text$$anonymous$$eshProUGUI.text inside the input field and even if I didn't type a space it was adding a space to the end of the string that I couldn't see in the inspector. So i switched to populate the string pulling from the T$$anonymous$$P_InputField.text then added a OnValueChanged listener to remove any spaces from the input field.