I have a situation in ASP.NET C# wherein for example I have the email address hello#gmail.com but I need to have the #gmail.com portion removed for all email input. Please help. Thanks :)
You can use MailAddress Class (System.Net.Mail):
string mailAddress = "hello#gmail.com";
var mail = new MailAddress(mailAddress);
string userName = mail.User; // hello
string host = mail.Host; // gmail.com
string address = mail.Address; // hello#gmail.com
In the case of wrong e-mail address (eg. lack of at sign or more than one) you have to catch FormatException, for example:
string mailAddress = "hello#gmail#";
var mail = new MailAddress(mailAddress); // error: FormatException
If you don't want to verify e-mail address, you can use Split method from string:
string mailAddress = "hello#gmail.com";
char atSign = '#';
string user = mailAddress.Split(atSign)[0]; // hello
string host = mailAddress.Split(atSign)[1]; // gmail.com
email = email.Substring(0, email.IndexOf('#'));
Like this:
new MailAddress(someString).User
If the email address is invalid, this will throw an exception.
If you also need to validate the email address, you should write new MaillAddress(someString) inside of a catch block; this is the best way to validate email addresses in .Net.
Related
There is an hyphen in the domain name.
sendToEmail = "abc#domain-self.com";
MailMessage message = new MailMessage(UserName, sendToEmail, EmailSubject, "");
This Code throws error:
The specified string is not in the form required for an e-mail address.
If there is no hyphen in the email then it works correctly.
How to resolve this?
I have a scenario, to convert the valid email address to test account by adding "test-" in the email address domain. So that on the testing environment it won't reach to the actual recipients. Also I adding my email address in the Bcc to verify that email content.
What I have tried so far:
{
MailMessage msg = new MailMessage();
// already valided the "emailAddress" is the valid one or not
msg.To.Add(new MailAddress(ToTestAccount(emailAddress)));
// other code ...
}
Calling the method ToTestAccount() to add the "test-" in the email address.
private string ToTestAccount(string emailAddress)
{
var userAlias = emailAddress.Split('#')[0];
var host = emailAddress.Split('#')[1].Split('.')[0];
var hostDomain = emailAddress.Split('#')[1];
var indexOfDot = hostDomain.IndexOf('.');
var domain = hostDomain.Substring(indexOfDot, hostDomain.Length - indexOfDot);
return userAlias + "#test-" + host + domain;
}
The functionality produce my expected result. Sample data and expected output:
Email Address | Expected
----------------------------------------------------------
arulkumar#gmail.com | arulkumar#test-gmail.com
arul.kumar#gmail.com | arul.kumar#test-gmail.com
arulkumar4#gmail.co.in | arulkumar4#test-gmail.co.in
arul.kumar4#gmail.co.in | arul.kumar4#test-gmail.co.in
But is there any other way to achieve the expected result, I mean using less string funtions or the best practice to achieve it?
C# Fiddle for the same: https://rextester.com/LPZI50439
For some reason, I'm not able to use SpecifiedPickupDirectory option, so I'm triggering the actual email.
You can use the MailAddress properties which would result in less string manipulation and handle some of the weird varieties of valid email addresses.
private string ToTestAccount(string emailAddress)
{
var originalEmailAddress = new MailAddress(emailAddress);
return $"{originalEmailAddress.User}#test-{originalEmailAddress.Host}";
}
Or if you need to support display names you could have an extension method:
public static MailAddress Testing(this MailAddress address)
{
return string.IsNullOrEmpty(address.DisplayName)
? new MailAddress($"{address.User}#test-{address.Host}")
: new MailAddress($"{address.User}#test-{address.Host}", address.DisplayName);
}
Which would allow usage like this:
{
MailMessage msg = new MailMessage();
// already valided the "emailAddress" is the valid one or not
msg.To.Add(new MailAddress(emailAddress).Testing()));
msg.To.Add(new MailAddress(aDifferentEmailAddress, displayName).Testing()));
// other code ...
}
You can use replace in your case.
private string ToTestAccount(string emailAddress)
{
return emailAddress == null ? emailAddress : emailAddress.Replace("#","#test-");
}
Please note that this solution is valid only in case if you need not to deliver the message to the real user. If you need to change domain to deliver it it may not work as email may contain more than one # symbol. As #andyb952 mentioned in a comment it's very rare but possible.
I have an ASP.NET 4.0 aspx page from which I wish to send an email to the recipient specified in a text box named "supervisoremailTextBox". Is there any way that I can specify a variable as the recipient email address. The code I have used which doesn't work is shown below:
MailAddress fromAddress = new MailAddress("address#domain.co.uk", "Sender Name");
MailAddress toAddress = new MailAddress("supervisoremailTextBox.Value");
message.From = fromAddress;
message.To.Add(toAddress);
Sorry if this a really dumb question and thanks in advance for your help.
When you use MailAddress, you need to use a valid email address.
The string "supervisoremailTextBox.Value" is not a valid email address.
If you mean to use the value of a textbox with the ID supervisoremailTextBox, use:
MailAddress toAddress = new MailAddress(supervisoremailTextBox.Value);
Note that I have dropped the " to ensure you are not passing in a string.
Try this instead:
MailAddress toAddress = new MailAddress(supervisoremailTextBox.Value);
I have done this before without any issue but now I don't know what's wrong. I have a web page with a button for email which I want to send some data to email addresses with.
I asked our web hosting company for server details and the response I got was:
"You can use the following details for mail.
Incoming mail server: mail.ourSite.com Outgoing mail server: mail.ourSite.com
Username and password are the email address and password associated with the email address.
"
I am not sure about the last line but I created a new email address in the web host's control panel.
The code I use is:
// instantiate a new mail definition and load an html
// template into a string which I replace values in
// then the rest of the code below
md.Subject = String.Format("{0} {1} {2}", emailSubject, firstName, lastName);
MailMessage msg = md.CreateMailMessage(emailAddress, replacements, emailBody, new Control());
md.IsBodyHtml = true;
SmtpClient sc = new SmtpClient(emailServer);
sc.Credentials = new NetworkCredential(emailUsername, emailPassword);
try
{
sc.Send(msg);
}
emailServer - mail.ourSite.com (dummy value in this post)
emailUsername - the email address I created in the control panel
emailPassword - the password for the email above
The error I have is that when I send emails to other domains than our own I get
"Bad sequence of commands. The server response was: This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server."
When I email to an address within our host then it works fine.
The support is not very supportive so I am asking here what you might think the problem could be? I find it strange that I use the password for an email address I created, should it really be like that?
I think that you are using the wrong email address for the NetworkCredential. It should be the one for your email account that you got from the one providing emailServer.
Try this ..
msg.UseDefaultCredentials = false;
NetworkCredential MyCredential = new NetworkCredential("Email", "Password");
msg.Credentials = MyCredential;
here is code to send mail..
i hope i will helpful to you..
using System.Web.Mail;
using System;
public class MailSender
{
public static bool SendEmail(
string pGmailEmail,
string pGmailPassword,
string pTo,
string pSubject,
string pBody,
System.Web.Mail.MailFormat pFormat,
string pAttachmentPath)
{
try
{
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}
System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
System.Web.Mail.SmtpMail.Send(myMail);
return true;
}
catch (Exception ex)
{
throw;
}
}
}
I need to create an plain-test email in code. This is required because the information in the email will be read by an application.
I've created the following value in an constant string as setup for my email. These are the fields that I want to be in the e-mail because the application requires them.
public static string TestMail = #"
[Begin Message]
Name = {0}
Phone = {1}
Postalcode = {2}
HomeNumber = {3}
[End message]";
When sending the email using the code below, the application which needs to read information from the email, receives it as following;
=0D=0A [Begin Message]=0D=0A Name =3D nam=
e=0D=0A Phone =3D 0612345678=0D=0A Postalcode =3D =
1234ab=0D=0A HomeNumber =3D 5=0D=0A [End messa=
ge]=0D=0A =20
The code I used to send this email is as following;
var mailBody = String.Format(Constants.TestMail, name, phone, postalCode, homeNumber);
var mail = new MailMessage
{
Subject = Constants.Subject,
Body = mailBody,
IsBodyHtml = false,
};
mail.To.Add(receveiver);
var smtpClient = new SmtpClient();
smtpClient.Send(mail);
This isn't the result I expected and after digging around a bit I found out that the problem lied in the fact that it still seems to be an HTML-email while I need it to be plain-text. While reading about this problem I found this example in VB.net on the internet. So i modified the constant to the one below;
public static string TestMail = #"[Begin message]\r\nName = {0}\r\nPhone = {1}\r\nPostalcode = {2}\r\nHomenumber = {3}\r\n[End message]";
Then I used the following code to create and sent the email to my client (testing in outlook)
var mail = new MailMessage
{
Subject = Constants.Subject,
};
var alternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailBody, Encoding.ASCII,"text/plain");
mail.AlternateViews.Add(alternateView);
mail.To.Add(receveiver);
var smtpClient = new SmtpClient();
smtpClient.Send(mail);
After running this code i'm receiving an email in my outlook (can't test the application at the moment) containing the content below;
[Start message]\r\nName = John\r\nPhone = 0612345678\r\nPostalcode = 1234ab\r\nHomeNumber = 5\r\n[End Message]
The last result doesn't seem an plain-text email to me. Is it just outlook 2007 having problems to show the email? Or am I still missing something? I hope someone can help me out here and can tell me what's going wrong.
You should remove # character because then it will correctly handle escape characters. If you have # then all escape characters are treated as a plain text instead of new line etc.