Sending Emails with BCC list not working - asp.net

I am trying to send emails to a single 'To' recipient, and a list of 'Bcc' recipients.
The list of Bcc recipients is a list of string, and they are successfully being added to the mailMessage's Bcc collection, but not actually being sent. If I add the same list to the message's 'Cc' collection it works fine. Just not the Bcc collection.
The code I'm using is this:
public void SendEmailMessage(String FromAddress, String ToAddress, String Subject, String Body, List<String> CCAddress, List<String> BccAddress, String Filepath)
{
using (SmtpClient mailClient = new SmtpClient())
{
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(FromAddress);
mailMessage.To.Add(new MailAddress(ToAddress));
foreach (String _email in CCAddress)
{
mailMessage.CC.Add(new MailAddress(_email));
}
foreach (String _email in BccAddress)
{
mailMessage.Bcc.Add(new MailAddress(_email));
}
mailMessage.Priority = MailPriority.Normal;
mailMessage.Subject = Subject;
if (Filepath != string.Empty)
{
Attachment _attachment = new Attachment(Filepath, MediaTypeNames.Application.Octet);
mailMessage.Attachments.Add(_attachment);
}
AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(GetTextonly(Body), null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");
mailMessage.AlternateViews.Add(plainTextView);
mailMessage.AlternateViews.Add(htmlView);
SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
smtpClient.Send(mailMessage);
}
}
any ideas?

one thing i didn't mention is that the mail is put in a pickup directory rather than sent direct.
I found a blog which explains that bcc addresses aren't sent if using a pickup directory, and you can put them in the retry directory instead. This solved my problem with an easy fix:
Unable to send Bcc using System.Net.Mail when specifying a Pickup Directory(Exchange 2007/Exchange 2010) in code

As a workaround, you could send your email explicitly to the BCC address.
After you've successfully sent your email:
mailClient.Send(mailMessage);
Clear the To address collection, then add your BCC address as a To address, and resend.
mailMessage.To.Clear(); // clear the existing To & Cc fields
mailMessage.Cc.Clear();
mailMessage.To.Add(new MailAddress("bcc#address.com","CopyAddress"));
mailClient.Send(mailMessage);

I created a test application and ran SmptForDev to capture any emails going out from my local IIS. I used the code below and it works fine. All I've really done to your code is tidy it up and it works fine. I also decompiled System.Net.Mail.SmtpClient to see what it does under the hood, the To address and Bcc addresses are all put into one collection, if one address is sending it's good to assume they all are.
public void SendEmailMessage(string fromAddress, string toAddress, string subject, string body, IEnumerable<string> ccAddress, IEnumerable<string> bccAddress, string filepath)
{
using (var mailClient = new SmtpClient())
{
var mailMessage = new MailMessage(fromAddress, toAddress);
foreach (var email in ccAddress)
{
mailMessage.CC.Add(new MailAddress(email));
}
foreach (var email in bccAddress)
{
mailMessage.Bcc.Add(new MailAddress(email,"Matty Boy"));
}
mailMessage.Priority = MailPriority.Normal;
mailMessage.Subject = subject;
if (!string.IsNullOrEmpty(filepath))
{
var attachment = new Attachment(filepath, MediaTypeNames.Application.Octet);
mailMessage.Attachments.Add(attachment);
}
var plainTextView = AlternateView.CreateAlternateViewFromString(GetTextonly(body), null, "text/plain");
var htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
mailMessage.AlternateViews.Add(plainTextView);
mailMessage.AlternateViews.Add(htmlView);
mailClient.Send(mailMessage);
}
}

Related

How to send email from an asp.net application using gmail smtp [duplicate]

Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show.
Is it possible to do it?
Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting.
If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the fromPassword constant instead of your standard Gmail password.
If it is disabled, then you have to turn on Less secure app access, which is not recommended! So better enable the 2-Step verification.
The above answer doesn't work. You have to set DeliveryMethod = SmtpDeliveryMethod.Network or it will come back with a "client was not authenticated" error. Also it's always a good idea to put a timeout.
Revised code:
using System.Net.Mail;
using System.Net;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#yahoo.com", "To Name");
const string fromPassword = "password";
const string subject = "test";
const string body = "Hey now!!";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Edit 2022
Starting May 30, 2022, ​​Google will no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.
But you still can send E-Mail via your gmail account.
Go to https://myaccount.google.com/security and turn on two step verification. Confirm your account by phone if needed.
Click "App Passwords", just below the "2 step verification" tick.
Request a new password for the mail app.
Now just use this password instead of the original one for you account!
public static void SendMail2Step(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body, string[] FileNames) {
var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = true
};
smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!
var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, "SendMail2Step"), new System.Net.Mail.MailAddress(To, To));
smtpClient.Send(message);
}
Use like this:
SendMail2Step("smtp.gmail.com", 587, "youraccount#gmail.com",
"yjkjcipfdfkytgqv",//This will be generated by google, copy it here.
"recipient#barcodes.bg", "test message subject", "Test message body ...", null);
For the other answers to work "from a server" first Turn On Access for less secure apps in the gmail account. This will be deprecated 30 May 2022
Looks like recently google changed it's security policy. The top rated answer no longer works, until you change your account settings as described here: https://support.google.com/accounts/answer/6010255?hl=en-GB
As of March 2016, google changed the setting location again!
This is to send email with attachement.. Simple and short..
source: http://coding-issues.blogspot.in/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);
}
Google may block sign in attempts from some apps or devices that do not use modern security standards. Since these apps and devices are easier to break into, blocking them helps keep your account safer.
Some examples of apps that do not support the latest security standards include:
The Mail app on your iPhone or iPad with iOS 6 or below
The Mail app on your Windows phone preceding the 8.1 release
Some Desktop mail clients like Microsoft Outlook and Mozilla Thunderbird
Therefore, you have to enable Less Secure Sign-In in your google account.
After sign into google account, go to:
https://myaccount.google.com/lesssecureapps
or
https://www.google.com/settings/security/lesssecureapps
In C#, you can use the following code:
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("email#gmail.com");
mail.To.Add("somebody#domain.com");
mail.Subject = "Hello World";
mail.Body = "<h1>Hello</h1>";
mail.IsBodyHtml = true;
mail.Attachments.Add(new Attachment("C:\\file.zip"));
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
smtp.Credentials = new NetworkCredential("email#gmail.com", "password");
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
For me to get it to work, i had to enable my gmail account making it possible for other apps to gain access. This is done with the "enable less secure apps" and also using this link:
https://accounts.google.com/b/0/DisplayUnlockCaptcha
Here is my version: "Send Email In C # Using Gmail".
using System;
using System.Net;
using System.Net.Mail;
namespace SendMailViaGmail
{
class Program
{
static void Main(string[] args)
{
//Specify senders gmail address
string SendersAddress = "Sendersaddress#gmail.com";
//Specify The Address You want to sent Email To(can be any valid email address)
string ReceiversAddress = "ReceiversAddress#yahoo.com";
//Specify The password of gmial account u are using to sent mail(pw of sender#gmail.com)
const string SendersPassword = "Password";
//Write the subject of ur mail
const string subject = "Testing";
//Write the contents of your mail
const string body = "Hi This Is my Mail From Gmail";
try
{
//we will use Smtp client which allows us to send email using SMTP Protocol
//i have specified the properties of SmtpClient smtp within{}
//gmails smtp server name is smtp.gmail.com and port number is 587
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(SendersAddress, SendersPassword),
Timeout = 3000
};
//MailMessage represents a mail message
//it is 4 parameters(From,TO,subject,body)
MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
/*WE use smtp sever we specified above to send the message(MailMessage message)*/
smtp.Send(message);
Console.WriteLine("Message Sent Successfully");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
I hope this code will work fine. You can have a try.
// Include this.
using System.Net.Mail;
string fromAddress = "xyz#gmail.com";
string mailPassword = "*****"; // Mail id password from where mail will be sent.
string messageBody = "Write the body of the message here.";
// Create smtp connection.
SmtpClient client = new SmtpClient();
client.Port = 587;//outgoing port for the mail.
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(fromAddress, mailPassword);
// Fill the mail form.
var send_mail = new MailMessage();
send_mail.IsBodyHtml = true;
//address from where mail will be sent.
send_mail.From = new MailAddress("from#gmail.com");
//address to which mail will be sent.
send_mail.To.Add(new MailAddress("to#example.com");
//subject of the mail.
send_mail.Subject = "put any subject here";
send_mail.Body = messageBody;
client.Send(send_mail);
Source : Send email in ASP.NET C#
Below is a sample working code for sending in a mail using C#, in the below example I am using google’s smtp server.
The code is pretty self explanatory, replace email and password with your email and password values.
public void SendEmail(string address, string subject, string message)
{
string email = "yrshaikh.mail#gmail.com";
string password = "put-your-GMAIL-password-here";
var loginInfo = new NetworkCredential(email, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress(address));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
To avoid security issues in Gmail, you should generate an app password first from your Gmail settings and you can use this password instead of a real password to send an email even if you use two steps verification.
Include this,
using System.Net.Mail;
And then,
MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential("mail-id#gmail.com","password");
client.EnableSsl = true;
client.Send(sendmsg);
If you want to send background email, then please do the below
public void SendEmail(string address, string subject, string message)
{
Thread threadSendMails;
threadSendMails = new Thread(delegate()
{
//Place your Code here
});
threadSendMails.IsBackground = true;
threadSendMails.Start();
}
and add namespace
using System.Threading;
Try This,
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your_email_address#gmail.com");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
use this way
MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = Convert.ToInt32("587");
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("mail-id#gmail.com","MyPassWord");
client.Send(sendmsg);
Don't forget this :
using System.Net;
using System.Net.Mail;
From 1 Jun 2022, ​​Google has added some security features
Google is no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password or send mail directly using username and password of google account. But you still can send E-Mail via your gmail account using generating app password.
Below are the steps for generate new password.
Go to https://myaccount.google.com/security
Turn on two step verification.
Confirm your account by phone if needed.
Click "App Passwords", just below the "2 step verification" tick. Request a new password for the mail app.
Now we have to use this password for sending mail instead of the original password of your account.
Below is the example code for sending mail
public static void SendMailFromApp(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body) {
var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = true
};
smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!
var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, "SendMail2Step"), new System.Net.Mail.MailAddress(To, To));
smtpClient.Send(message);
}
You can to call method like below
SendMailFromApp("smtp.gmail.com", 25, "mygmailaccount#gmail.com",
"tyugyyj1556jhghg",//This will be generated by google, copy it here.
"mailme#gmail.com", "New Mail Subject", "Body of mail from My App");
Changing sender on Gmail / Outlook.com email:
To prevent spoofing - Gmail/Outlook.com won't let you send from an arbitrary user account name.
If you have a limited number of senders you can follow these instructions and then set the From field to this address: Sending mail from a different address
If you are wanting to send from an arbitrary email address (such as a feedback form on website where the user enters their email and you don't want them emailing you directly) about the best you can do is this :
msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));
This would let you just hit 'reply' in your email account to reply to the fan of your band on a feedback page, but they wouldn't get your actual email which would likely lead to a tonne of spam.
If you're in a controlled environment this works great, but please note that I've seen some email clients send to the from address even when reply-to is specified (I don't know which).
I had the same issue, but it was resolved by going to gmail's security settings and Allowing Less Secure apps.
The Code from Domenic & Donny works, but only if you enabled that setting
If you are signed in (to Google) you can follow this link and toggle "Turn on" for "Access for less secure apps"
using System;
using System.Net;
using System.Net.Mail;
namespace SendMailViaGmail
{
class Program
{
static void Main(string[] args)
{
//Specify senders gmail address
string SendersAddress = "Sendersaddress#gmail.com";
//Specify The Address You want to sent Email To(can be any valid email address)
string ReceiversAddress = "ReceiversAddress#yahoo.com";
//Specify The password of gmial account u are using to sent mail(pw of sender#gmail.com)
const string SendersPassword = "Password";
//Write the subject of ur mail
const string subject = "Testing";
//Write the contents of your mail
const string body = "Hi This Is my Mail From Gmail";
try
{
//we will use Smtp client which allows us to send email using SMTP Protocol
//i have specified the properties of SmtpClient smtp within{}
//gmails smtp server name is smtp.gmail.com and port number is 587
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(SendersAddress, SendersPassword),
Timeout = 3000
};
//MailMessage represents a mail message
//it is 4 parameters(From,TO,subject,body)
MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
/*WE use smtp sever we specified above to send the message(MailMessage message)*/
smtp.Send(message);
Console.WriteLine("Message Sent Successfully");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
Google has removed the less secure apps setting from our Google accounts, this means that we can no longer send emails from the SMTP server using our actual google passwords. We need to either use Xoauth2 and authorize the user or create a an apps password on an account that has 2fa enabled.
Once created an apps password can be used in place of your standard gmail password.
class Program
{
private const string To = "test#test.com";
private const string From = "test#test.com";
private const string GoogleAppPassword = "XXXXXXXX";
private const string Subject = "Test email";
private const string Body = "<h1>Hello</h1>";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential(From , GoogleAppPassword),
EnableSsl = true,
};
var mailMessage = new MailMessage
{
From = new MailAddress(From),
Subject = Subject,
Body = Body,
IsBodyHtml = true,
};
mailMessage.To.Add(To);
smtpClient.Send(mailMessage);
}
}
Quick fix for SMTP username and password not accepted error
After google update, This is the valid method to send an email using c# or .net.
using System;
using System.Net;
using System.Net.Mail;
namespace EmailApp
{
internal class Program
{
public static void Main(string[] args)
{
String SendMailFrom = "Sender Email";
String SendMailTo = "Reciever Email";
String SendMailSubject = "Email Subject";
String SendMailBody = "Email Body";
try
{
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com",587);
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage email = new MailMessage();
// START
email.From = new MailAddress(SendMailFrom);
email.To.Add(SendMailTo);
email.CC.Add(SendMailFrom);
email.Subject = SendMailSubject;
email.Body = SendMailBody;
//END
SmtpServer.Timeout = 5000;
SmtpServer.EnableSsl = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new NetworkCredential(SendMailFrom, "Google App Password");
SmtpServer.Send(email);
Console.WriteLine("Email Successfully Sent");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
}
}
For creating the app password, you can follow this article:
https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html
Here is one method to send mail and getting credentials from web.config:
public static string SendEmail(string To, string Subject, string Msg, bool bodyHtml = false, bool test = false, Stream AttachmentStream = null, string AttachmentType = null, string AttachmentFileName = null)
{
try
{
System.Net.Mail.MailMessage newMsg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["mailCfg"], To, Subject, Msg);
newMsg.BodyEncoding = System.Text.Encoding.UTF8;
newMsg.HeadersEncoding = System.Text.Encoding.UTF8;
newMsg.SubjectEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
if (AttachmentStream != null && AttachmentType != null && AttachmentFileName != null)
{
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentStream, AttachmentFileName);
System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
disposition.FileName = AttachmentFileName;
disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;
newMsg.Attachments.Add(attachment);
}
if (test)
{
smtpClient.PickupDirectoryLocation = "C:\\TestEmail";
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
}
else
{
//smtpClient.EnableSsl = true;
}
newMsg.IsBodyHtml = bodyHtml;
smtpClient.Send(newMsg);
return SENT_OK;
}
catch (Exception ex)
{
return "Error: " + ex.Message
+ "<br/><br/>Inner Exception: "
+ ex.InnerException;
}
}
And the corresponding section in web.config:
<appSettings>
<add key="mailCfg" value="yourmail#example.com"/>
</appSettings>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="yourmail#example.com">
<network defaultCredentials="false" host="mail.exapmple.com" userName="yourmail#example.com" password="your_password" port="25"/>
</smtp>
</mailSettings>
</system.net>
Try this one
public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)
{
MailMessage mailMessage = new MailMessage();
MailAddress mailAddress = new MailAddress("abc#gmail.com", "Sender Name"); // abc#gmail.com = input Sender Email Address
mailMessage.From = mailAddress;
mailAddress = new MailAddress(receiverEmail, ReceiverName);
mailMessage.To.Add(mailAddress);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
SmtpClient mailSender = new SmtpClient("smtp.gmail.com", 587)
{
EnableSsl = true,
UseDefaultCredentials = false,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("abc#gmail.com", "pass") // abc#gmail.com = input sender email address
//pass = sender email password
};
try
{
mailSender.Send(mailMessage);
return true;
}
catch (SmtpFailedRecipientException ex)
{
// Write the exception to a Log file.
}
catch (SmtpException ex)
{
// Write the exception to a Log file.
}
finally
{
mailSender = null;
mailMessage.Dispose();
}
return false;
}
You can try Mailkit. It gives you better and advance functionality for send mail. You can find more from this Here is an example
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress("FromName", "YOU_FROM_ADDRESS#gmail.com"));
message.To.Add(new MailboxAddress("ToName", "YOU_TO_ADDRESS#gmail.com"));
message.Subject = "MyEmailSubject";
message.Body = new TextPart("plain")
{
Text = #"MyEmailBodyOnlyTextPart"
};
using (var client = new SmtpClient())
{
client.Connect("SERVER", 25); // 25 is port you can change accordingly
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("YOUR_USER_NAME", "YOUR_PASSWORD");
client.Send(message);
client.Disconnect(true);
}
Copying from another answer, the above methods work but gmail always replaces the "from" and "reply to" email with the actual sending gmail account. apparently there is a work around however:
http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html
"3. In the Accounts Tab, Click on the link "Add another email address you own" then verify it"
Or possibly this
Update 3: Reader Derek Bennett says, "The solution is to go into your gmail Settings:Accounts and "Make default" an account other than your gmail account. This will cause gmail to re-write the From field with whatever the default account's email address is."
This is no longer supported incase you are trying to do this now.
https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637960864118404117-800836189&p=less-secure-apps&rd=1#zippy=
If your Google password doesn't work, you may need to create an app-specific password for Gmail on Google.
https://support.google.com/accounts/answer/185833?hl=en

aws simple email service not working with godaddy hosting asp.net

I was earlier using godaddy email services to send emails from my web application in asp.net. But now I moved to aws ses as it is fast.
The thing is in development environment(Local) aws email is working fine and emails are going but when I am deploying it in godaddy server then no email is going. Do I need to do any settings at godaddy server level or it is my code fault? My website is in shared hosting environment. Is it the reason.
Is this related to MX records?
Here is my code
string UserName = ConfigurationManager.AppSettings["UserName"];
string EmailFrom = ConfigurationManager.AppSettings["EmailFrom"];
string EmailFromDisplayName = ConfigurationManager.AppSettings["EmailFromDisplayName"];
string EmailFromPwd = ConfigurationManager.AppSettings["EmailFromPwd"];
string EmailBcc = ConfigurationManager.AppSettings["EmailBcc"];
bool EmailIsSSL = Convert.ToBoolean(ConfigurationManager.AppSettings["EmailIsSSL"]);
int EmailPort = Convert.ToInt32(ConfigurationManager.AppSettings["EmailPort"]);
string EmailHost = ConfigurationManager.AppSettings["EmailHost"];
//Create the msg object to be sent
MailMessage mailMessage = new MailMessage();
//Default email message
mailMessage.Bcc.Add(EmailBcc);
//Configure the address we are sending the mail from
MailAddress address = new MailAddress(EmailFrom, EmailFromDisplayName);
mailMessage.From = address;
//Loop all to recepients
foreach(string emailTo in toAddress)
{
mailMessage.To.Add(emailTo);
}
//Loop to add all Bcc addresses...
foreach (string emailBcc in bccAddress)
{
mailMessage.Bcc.Add(emailBcc);
}
//Loop to add all CC addresses...
foreach (string emailCc in ccAddress)
{
mailMessage.CC.Add(emailCc);
}
//Add attachments...
foreach (string filePathWithName in relativeFilePathsToBeAttached)
{
if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(filePathWithName)))
{
Attachment data = new Attachment(
System.Web.HttpContext.Current.Server.MapPath(filePathWithName),
MediaTypeNames.Application.Octet);
// your path may look like Server.MapPath("~/file.ABC")
mailMessage.Attachments.Add(data);
}
}
mailMessage.Subject = mailSubject;
mailMessage.Body = mailBody;
mailMessage.IsBodyHtml = IsBodyHtml;
//Configure an SmtpClient to send the mail.
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = EmailIsSSL;
client.Host = EmailHost;
client.Port = EmailPort;
//Setup credentials to login to our sender email address ("UserName", "Password")
//NetworkCredential credentials = new NetworkCredential(EmailFrom, EmailFromPwd);
NetworkCredential credentials = new NetworkCredential(UserName, EmailFromPwd);
client.UseDefaultCredentials = true;
client.Credentials = credentials;
if (ConfigurationManager.AppSettings["IsMailEnabled"].ToString() == "true")
{
client.Send(mailMessage);
}
I am getting this error on server
Failure sending mail.System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed. at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller) at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) at System.Net.Mail.SmtpClient.Send(MailMessage message) at TestCookie.ExecuteSendEmail(String mailBody, String mailSubject, List1 toAddress, List1 bccAddress, List1 ccAddress, List1 relativeFilePathsToBeAttached, Boolean IsBodyHtml)
The issue was with port number. I was using 587 and 25 and it is not working. But when I used 2587 and it worked for me. I don't know how. If someone can explain then that will help.

Activation code is not displaying in url after click on the link

I am sending a link using email to create password but while sending link in an email i have attach my Activation Code also to display with link but it is not displaying when i click on link though in debugging i'm getting the link with Activation Code. Below is my code to add link in Body section
body+=#"<br /><a href='http://localhost:49234/Index.aspx?ActivationCode='"+objUserDetailsBE.ActivationCode+"'>Create a login to account</a>";
I am getting only till http://localhost:49234/Index.aspx?ActivationCode= in browser after click on the link Please let me know where i am doing wrong.
Adding code as per in comments:
string emailAddress = txtEmailAddress.Text;
string subject = "Login Credentials For Nth Star";
string body = string.Format("Hello,");
body+=#"<br /><a href='http://localhost:49234/Index.aspx?ActivationCode='"+objUserDetailsBE.ActivationCode+"'>Create a login to account</a>";
Email.SendMail(objemail, emailAddress, subject, body, "");
and below is my 'SendMail' method
public static bool SendMail(EmailConfigurationBE objEmailConfig, string toEmailAddresses, string subject, string body, string mailAttachments)
{
char[] splitter = { ';' };
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(objEmailConfig.Email);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.Priority = MailPriority.High;
string[] multi = toEmailAddresses.Split(';');
string[] multipath = mailAttachments.Split(';');
foreach (string MultiemailId in multi)
{
mailMessage.To.Add(new MailAddress(MultiemailId));
}
if (mailMessage.To.Count > 0)
{
//Adding Multiple Attachments
if (mailAttachments != "")
{
foreach (string Multipath1 in multipath)
{
Attachment attachFile = new Attachment(Multipath1);
mailMessage.Attachments.Add(attachFile);
}
}
SmtpClient smtpClient = new SmtpClient();
try
{
smtpClient.Host = objEmailConfig.SMTPServer;
smtpClient.EnableSsl = EnableSsl;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = objEmailConfig.Email;
NetworkCred.Password =objEmailConfig.Password;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = NetworkCred;
smtpClient.Port =Convert.ToInt32(objEmailConfig.PortNumber);
smtpClient.Send(mailMessage);
return true;
}
catch
{
mailMessage = null;
smtpClient = null;
return false;
}
}
else
{
return false;
}
}
It looks like a simple quoting problem. Look
<a href='http://localhost:49234/Index.aspx?ActivationCode='"+objUserDetailsBE.ActivationCode+"'
In here you have a single quote before http, another one after ActivationCode= and third one at the end. Looks like one is redundant, and that breaks your markup.
Correct version:
body+=#"<br /><a href='http://localhost:49234/Index.aspx?ActivationCode="+objUserDetailsBE.ActivationCode+"'>Create a login to account</a>";
The only change I did was to remove the single quote after ActivationCode=.
Also make sure the active code does not contain symbols like quotes or <>, that can also break the markup.

what is the mistake? (sending email in asp.net)

I am using this code for sending email in asp.net:
Using System.Net.Mail
public string SendEmail()
{
SmtpClient obj = new SmtpClient();
MailMessage Mailmsg = new MailMessage();
Mailmsg.To.Clear();
Recievers = new MailAddressCollection();
Recievers.Add(txtToAddress.Text);
SenderName = "Info";
SenderEmail = txtFromAddress.Text;
Subject = "subj";
Body = "body";
UseBcc = false;
if (UseBcc)
{
foreach (MailAddress RecieverItem in Recievers)
{
Mailmsg.Bcc.Add(RecieverItem);
}
}
else
{
foreach (MailAddress RecieverItem in Recievers)
{
Mailmsg.To.Add(RecieverItem);
}
}
Mailmsg.From = new MailAddress(SenderEmail, SenderName, System.Text.Encoding.UTF8);
Mailmsg.Subject = Subject;
Mailmsg.SubjectEncoding = Encoding.UTF8;
Mailmsg.BodyEncoding = System.Text.Encoding.UTF8;
Mailmsg.IsBodyHtml = false;
obj.Host = mail.domain.com;
System.Net.NetworkCredential BasicAuthenticationInfo = new System.Net.NetworkCredential("info#domain.com", "password");
obj.UseDefaultCredentials = false;
obj.Credentials = BasicAuthenticationInfo;
Mailmsg.Body = Body;
Mailmsg.IsBodyHtml = true;
try
{
obj.Send(Mailmsg);
return "sent";
}
catch (Exception ex)
{
return ex.ToString();
}
}
It correctly sends emails to recievers which are defined in my domain (like mail#domain.com), but I cannot send email to other mail servers (like mail#yahoo.com).
What is wrong in my code?
(May it relate to SmtpClient properties? I have set smtpclient.host to mail.mydomain.com
and use username and password of one of my mail accounts which are defined in my domain)
Thanks
It must be something related to your exchange server. there are transport rules in exchange which define how you can communicate with the outside world.
http://www.msexchange.org/articles_tutorials/exchange-server-2007/management-administration/restricting-users-send-receive-external-messages-exchange-server-2007.html
you must be getting some exception while sending email to outside network
System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.1.1 User unknown
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
If this is error you are getting this mean your exchange is not supported to send email directly to outside network. as I am no MS exchange expert but i have been using a exchange server configured in my network that can't send email to outside network but we enable email forwarding to contacts.
May be this can help you. http://www.petri.co.il/configuring-exchange-2007-send-connectors.htm
also i would suggest you share this problem on https://serverfault.com/

Send mail using SMTP server

Hell Guys!
I have used SMTP server to send mail as per below
public bool SendMail(string mailFrom, string mailTo, string mailCC, string mailBCC, string subject, string body, string attachment, bool isBodyHtml)
{
bool SendStatus = false;
System.Net.Mail.MailMessage mailMesg = new System.Net.Mail.MailMessage(mailFrom, mailTo);
if (mailCC != string.Empty)
mailMesg.CC.Add(mailCC);
if (mailBCC != string.Empty)
mailMesg.Bcc.Add(mailBCC);
if (!string.IsNullOrEmpty(attachment))
{
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(attachment);
mailMesg.Attachments.Add(attach);
}
mailMesg.Subject = subject;
mailMesg.Body = body;
mailMesg.IsBodyHtml = isBodyHtml;
mailMesg.ReplyTo = new System.Net.Mail.MailAddress(mailFrom);
System.Net.Mail.SmtpClient objSMTP = new System.Net.Mail.SmtpClient();
string Host = System.Configuration.ConfigurationManager.AppSettings["MailHost"].ToString();
string UserName = System.Configuration.ConfigurationManager.AppSettings["MailUserId"].ToString();
string password = System.Configuration.ConfigurationManager.AppSettings["MailPassword"].ToString();
objSMTP.Host = Host;
objSMTP.Port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["Port"].ToString());
objSMTP.Credentials = new System.Net.NetworkCredential(UserName, password);
objSMTP.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
try
{
objSMTP.Send(mailMesg);
SendStatus = true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
mailMesg.Dispose();
mailMesg = null;
}
return SendStatus;
}
I would like to know that Is it possible to send mail without username & password ?
If possible then can anyone please suggest me how to do that?
Sure, if your smtp server doesn't require cridentials you shouldn't specify em. Otherwise you should.
I think you need to white list the ip that you will send e-mail from which will be your server and this option is done on the mail account that you are going to send e-mails from.

Resources