I have smtp email functionality. it works for single address but has problem in multiple address.
i am passing multiple addresses using following line of code.
MailAddress to = new MailAddress("abc#gmail.com,xyz#gmail.com");
Please let me know the problem as i am not getting any error.
MailMessage msg = new MailMessage();
msg.Body = ....;
msg.To.Add(...);
msg.To.Add(...);
SmtpClient smtp = new SmtpClient();
smtp.Send(msg);
To is a MailAddressCollection, so you can add how many addresses you need.
If you need a display name, try this:
MailAddress to = new MailAddress(
String.Format("{0} <{1}>",display_name, address));
try this..
using System;
using System.Net.Mail;
public class Test
{
public static void Main()
{
SmtpClient client = new SmtpClient("smtphost", 25);
MailMessage msg = new MailMessage("x#y.com", "a#b.com,c#d.com");
msg.Subject = "sdfdsf";
msg.Body = "sdfsdfdsfd";
client.UseDefaultCredentials = true;
client.Send(msg);
}
}
I think you can use this code in order to have List of outgoing Addresses having a display Name (also different):
//1.The ACCOUNT
MailAddress fromAddress = new MailAddress("myaccount#myaccount.com", "my display name");
String fromPassword = "password";
//2.The Destination email Addresses
MailAddressCollection TO_addressList = new MailAddressCollection();
//3.Prepare the Destination email Addresses list
foreach (var curr_address in mailto.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
MailAddress mytoAddress = new MailAddress(curr_address, "Custom display name");
TO_addressList.Add(mytoAddress);
}
//4.The Email Body Message
String body = bodymsg;
//5.Prepare GMAIL SMTP: with SSL on port 587
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 30000
};
//6.Complete the message and SEND the email:
using (var message = new MailMessage()
{
From = fromAddress,
Subject = subject,
Body = body,
})
{
message.To.Add(TO_addressList.ToString());
smtp.Send(message);
}
StewieFG suggestion is valid but if you want to add the recipient name use this, with what Marco has posted above but is email address first and display name second:
msg.To.Add(new MailAddress("your#email1.com","Your name 1"));
msg.To.Add(new MailAddress("your#email2.com","Your name 2"));
My code to solve this problem:
private void sendMail()
{
//This list can be a parameter of metothd
List<MailAddress> lst = new List<MailAddress>();
lst.Add(new MailAddress("mouse#xxxx.com"));
lst.Add(new MailAddress("duck#xxxx.com"));
lst.Add(new MailAddress("goose#xxxx.com"));
lst.Add(new MailAddress("wolf#xxxx.com"));
try
{
MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = "10.15.130.28"; //or SMTP name
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("from#email.com", "password");
objeto_mail.From = new MailAddress("from#email.com");
//add each email adress
foreach (MailAddress m in lst)
{
objeto_mail.To.Add(m);
}
objeto_mail.Subject = "Sending mail test";
objeto_mail.Body = "Functional test for automatic mail :-)";
client.Send(objeto_mail);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
namespace WebForms.Code.Logging {
public class ObserverLogToEmail: ILog {
private string from;
private string to;
private string subject;
private string body;
private SmtpClient smtpClient;
private MailMessage mailMessage;
private MailPriority mailPriority;
private MailAddressCollection mailAddressCollection;
private MailAddress fromMailAddress, toMailAddress;
public MailAddressCollection toMailAddressCollection {
get;
set;
}
public MailAddressCollection ccMailAddressCollection {
get;
set;
}
public MailAddressCollection bccMailAddressCollection {
get;
set;
}
public ObserverLogToEmail(string from, string to, string subject, string body, SmtpClient smtpClient) {
this.from = from;
this.to = to;
this.subject = subject;
this.body = body;
this.smtpClient = smtpClient;
}
public ObserverLogToEmail(MailAddress fromMailAddress, MailAddress toMailAddress,
string subject, string content, SmtpClient smtpClient) {
try {
this.fromMailAddress = fromMailAddress;
this.toMailAddress = toMailAddress;
this.subject = subject;
this.body = content;
this.smtpClient = smtpClient;
mailAddressCollection = new MailAddressCollection();
} catch {
throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
}
}
public ObserverLogToEmail(MailAddressCollection fromMailAddressCollection,
MailAddressCollection toMailAddressCollection,
string subject, string content, SmtpClient smtpClient) {
try {
this.toMailAddressCollection = toMailAddressCollection;
this.ccMailAddressCollection = ccMailAddressCollection;
this.subject = subject;
this.body = content;
this.smtpClient = smtpClient;
} catch {
throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
}
}
public ObserverLogToEmail(MailAddressCollection toMailAddressCollection,
MailAddressCollection ccMailAddressCollection,
MailAddressCollection bccMailAddressCollection,
string subject, string content, SmtpClient smtpClient) {
try {
this.toMailAddressCollection = toMailAddressCollection;
this.ccMailAddressCollection = ccMailAddressCollection;
this.bccMailAddressCollection = bccMailAddressCollection;
this.subject = subject;
this.body = content;
this.smtpClient = smtpClient;
} catch {
throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
}
}#region ILog Members
// sends a log request via email.
// actual email 'Send' calls are commented out.
// uncomment if you have the proper email privileges.
public void Log(object sender, LogEventArgs e) {
string message = "[" + e.Date.ToString() + "] " + e.SeverityString + ": " + e.Message;
fromMailAddress = new MailAddress("", "HaNN", System.Text.Encoding.UTF8);
toMailAddress = new MailAddress("", "XXX", System.Text.Encoding.UTF8);
mailMessage = new MailMessage(fromMailAddress, toMailAddress);
mailMessage.Subject = subject;
mailMessage.Body = body;
// commented out for now. you need privileges to send email.
// _smtpClient.Send(from, to, subject, body);
smtpClient.Send(mailMessage);
}
public void LogAllEmails(object sender, LogEventArgs e) {
try {
string message = "[" + e.Date.ToString() + "] " + e.SeverityString + ": " + e.Message;
mailMessage = new MailMessage();
mailMessage.Subject = subject;
mailMessage.Body = body;
foreach(MailAddress toMailAddress in toMailAddressCollection) {
mailMessage.To.Add(toMailAddress);
}
foreach(MailAddress ccMailAddress in ccMailAddressCollection) {
mailMessage.CC.Add(ccMailAddress);
}
foreach(MailAddress bccMailAddress in bccMailAddressCollection) {
mailMessage.Bcc.Add(bccMailAddress);
}
if (smtpClient == null) {
var smtp = new SmtpClient {
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("yourEmailAddress", "yourPassword"),
Timeout = 30000
};
} else smtpClient.SendAsync(mailMessage, null);
} catch (Exception) {
throw;
}
}
}
I'm used "for" operator.
try
{
string s = textBox2.Text;
string[] f = s.Split(',');
for (int i = 0; i < f.Length; i++)
{
MailMessage message = new MailMessage(); // Create instance of message
message.To.Add(f[i]); // Add receiver
message.From = new System.Net.Mail.MailAddress(c);// Set sender .In this case the same as the username
message.Subject = label3.Text; // Set subject
message.Body = richTextBox1.Text; // Set body of message
client.Send(message); // Send the message
message = null; // Clean up
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
string[] MultiEmails = email.Split(',');
foreach (string ToEmail in MultiEmails)
{
message.To.Add(new MailAddress(ToEmail)); //adding multiple email addresses
}
MailAddress fromAddress = new MailAddress (fromMail,fromName);
MailAddress toAddress = new MailAddress(toMail,toName);
MailMessage message = new MailMessage(fromAddress,toAddress);
message.Subject = subject;
message.Body = body;
SmtpClient smtp = new SmtpClient()
{
Host = host, Port = port,
enabHost = "smtp.gmail.com",
Port = 25,
EnableSsl = true,
UseDefaultCredentials = true,
Credentials = new NetworkCredentials (fromMail, password)
};
smtp.send(message);
Related
I am setting up mail sending in my code as below
NetworkCredential nc = new NetworkCredential(ConfigurationManager.AppSettings["EmailId"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
MailMessage mm = new MailMessage();
mm.From = new MailAddress(SendEmailaddress);
mm.Body = "Test Mail";
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
mm.To.Add(ToEmailAddress);
mm.Subject = "Test";
SmtpClient sp = new SmtpClient();
sp.UseDefaultCredentials = false;
sp.Credentials = nc;
sp.EnableSsl = true;
sp.DeliveryMethod = SmtpDeliveryMethod.Network;
sp.Port = 587
sp.Host = ConfigurationManager.AppSettings["SMTP"].ToString();
sp.Send(mm);
A error is thrown at the time of mail sending. Mail sending works if I configure outlook on the same PC with these settings with TLS as encrypted connnection.
I have checked many posts where it is suggested that EnableSsl = true should be set for TLS to work but it does not work for me. It throws below error
Transaction failed. The server response was: 5.7.1
: Recipient address rejected: Access denied
at System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode
statusCode, String response) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender,
MailAddressCollection recipients, String deliveryNotify,
SmtpFailedRecipientException& exception) at
System.Net.Mail.SmtpClient.Send(MailMessage message)
I have hit a roadblock as no solution is found. is there a setting which needs to be done on server?
protected void SendAlertEmail(string smtpserver, string smtpport, string smtpuser, string smtppass, int ssl, int auth, string subject, string from, string to, string body)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(SplitEmailStrging(from), HttpUtility.HtmlDecode(Request.Form["senderName"]));
string emails = to;
if (emails.Contains(","))
{
string[] emailslist = Regex.Split(emails, #",");
foreach (string email in emailslist)
{
mail.To.Add(SplitEmailStrging(email));
}
}
else
{
if (emails.Contains("<"))
{
mail.To.Add(SplitEmailStrging(emails));
// Response.Write(SplitEmailStrging(emails));
}
else
{
mail.To.Add(emails);
// Response.Write(emails);
}
}
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = HttpUtility.HtmlDecode(body);
SmtpClient client = new SmtpClient(smtpserver);
if (int.Parse(smtpport) == 465)
{
client.Port = 25;
}
else
{
client.Port = int.Parse(smtpport);
}
if (ssl == 1)
{
client.EnableSsl = true;
}
else
{
client.EnableSsl = false;
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpuser, smtppass);
client.UseDefaultCredentials = false;
client.Credentials = credentials;
client.Send(mail);
}
catch (Exception ex)
{
Response.Write("Error: " + ex.InnerException.Message);
Response.End();
}
}
public void SendEmailWithAttachment(string pFrom, string pTo, string pSubject, string pBody, string pServer, string strAttachmentPDFFileNames)
{
try
{
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
string UserName = ConfigurationManager.AppSettings["SMTPUserName"];
string Password = ConfigurationManager.AppSettings["SMTPPassword"];
if (pTo.Contains(","))
{
string[] ToAdd = pTo.Split(new Char[] { ',' });
for (int i = 0; i < ToAdd.Length; i++)
{
Message.To.Add(ToAdd[i]);
}
}
else
{
Message.To.Add(pTo);
}
//System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(pTo);
//Message.To.Add(toAddress);
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress(pFrom);
Message.From = fromAddress;
Message.Subject = pSubject;
Message.Body = pBody;
Message.IsBodyHtml = true;
// Stream streamPDFImages = new MemoryStream(bytPDFImageFile);
//System.Net.Mail.SmtpClient
var smtpClient = new System.Net.Mail.SmtpClient();
{
Message.Attachments.Add(new System.Net.Mail.Attachment(strAttachmentPDFFileNames));
smtpClient.EnableSsl = true;
smtpClient.Host = pServer;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
smtpClient.Port = 465;
smtpClient.Send(Message);
}
}
catch (Exception Exc)
{
Exception ex = new Exception("Unable to send email . Please Contact administrator", Exc);
throw ex;
}
}
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("yourMail", "yourPassword");
smtp.EnableSsl = true;
MailMessage msg = new MailMessage(sendFrom, "yourMail");
msg.ReplyToList.Add(sendFrom);
msg.Subject = subject;
msg.Body = bodyTxt;
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(#"C:\Projects\EverydayProject\test.txt");
msg.Attachments.Add(attachment);
smtp.Send(msg);
Here is working code to send an email to gmail smtp. From what I see you don't set UseDefaultCredentials = false and you are using wrong port. Also you MUST NOT override exceptions like this., throw the initial exception. Also for this to work you need to turn off security setting in your Gmail account. You can google it.
In my system, I need send lot of emails. But, if I wait to send all the emails, the page gets too slow. I have tried to create an async class - but, the class starts and dies before the emails are even sent.
public class NotificationManager
{
public void SendNotification(NotificationData data)
{
data.MailTo = new WorkflowManager().GetEmailNotification((StatusType)data.Issue.StatusID, data.Issue.IssueId);
Task.Factory.StartNew(() =>
{
new MailManager().SendMessage(data);
});
}
}
class MailManager
{
static ILog log = log4net.LogManager.GetLogger(typeof(MailManager));
public static void SendMessage(Models.Extensions.NotificationData data)
{
var domain = string.Format("{0}/{1}", HttpContext.Current.Request.Url.AbsoluteUri.Replace("Edit", "IssueDetail"), data.Issue.IssueCode);
string type = new TypeManager().GetTypeById(data.Issue.IssueTypeID).Name;
string status = new StatusManager().GetStatusById(data.Issue.IssueTypeID).Name;
var body = string.Format("<h2>[{3}]</h2><br/>{0}<br/><br/><a href='{1}'>Issue</a><br/>[Ticket Number: {2}]",
data.Issue.Description, domain, data.Issue.IssueCode, type);
var subject = string.Format("[{0}] {1}", status, data.Issue.Summary);
SendEmailAwaitable(data.MailTo, subject, body);
log.Error("End Send Email Async");
}
private async Task<bool> SendEmailAwaitable(List<MailAddress> To, string Subject, string Body, bool isBodyHtml = true)
{
Settings s = new Settings();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(s.Email, s.EmailDisplayName);
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential = new NetworkCredential(s.EmailUserName, s.EmailPassword);
string userToken = Subject;
smtpClient.Host = s.EmailServer;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = Subject;
message.IsBodyHtml = isBodyHtml;
message.Body = Body;
foreach (var item in To)
{
userToken += ":To: " + item.Address;
message.To.Add(item);
}
smtpClient.SendCompleted += smtpClient_SendCompleted;
smtpClient.SendAsync(message, null);
await Task.Yield();
return true;
}
Trying to send an email through an SMTP server, but I'm getting a nondescript error on the smtp.Send(mail); snippet of code.
Server side, the relay IP addresses look correct. Scratching my head about what I'm missing.
MailMessage mail = new MailMessage();
mail.To.Add(txtEmail.Text);
mail.From = new MailAddress("no-reply#company.us");
mail.Subject = "Thank you for your submission...";
mail.Body = "This is where the body text goes";
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "mailex.company.us";
smtp.Credentials = new System.Net.NetworkCredential
("AdminName", "************");
smtp.EnableSsl = false;
if (fileuploadResume.HasFile)
{
mail.Attachments.Add(new Attachment(fileuploadResume.PostedFile.InputStream,
fileuploadResume.FileName));
}
smtp.Send(mail);
Try adding smtp.DeliveryMethod = SmtpDeliveryMethod.Network; prior to send.
For reference, here is my standard mail function:
public void sendMail(MailMessage msg)
{
string username = "username"; //email address or domain user for exchange authentication
string password = "password"; //password
SmtpClient mClient = new SmtpClient();
mClient.Host = "mailex.company.us";
mClient.Credentials = new NetworkCredential(username, password);
mClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mClient.Timeout = 100000;
mClient.Send(msg);
}
Typically called something like this:
MailMessage msg = new MailMessage();
msg.From = new MailAddress("fromAddr");
msg.To.Add(anAddr);
if (File.Exists(fullExportPath))
{
Attachment mailAttachment = new Attachment(fullExportPath); //attach
msg.Attachments.Add(mailAttachment);
msg.Subject = "Subj";
msg.IsBodyHtml = true;
msg.BodyEncoding = Encoding.ASCII;
msg.Body = "Body";
sendMail(msg);
}
else
{
//handle missing attachments
}
var client = new SmtpClient("smtp.gmail.com", 587);
Credentials = new NetworkCredential("sendermailadress", "senderpassword"),
EnableSsl = true
client.Send("sender mail adress","receiver mail adress", "subject", "body");
MessageBox.Show("mail sent");
This is Adil's answer formatted for C#:
public static class Email
{
private static string _senderEmailAddress = "sendermailadress";
private static string _senderPassword = "senderpassword";
public static void SendEmail(string receiverEmailAddress, string subject, string body)
{
try
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential(_senderEmailAddress, _senderPassword),
EnableSsl = true
};
client.Send(_senderEmailAddress, receiverEmailAddress, subject, body);
}
catch (Exception e)
{
Console.WriteLine("Exception sending email." + Environment.NewLine + e);
}
}
}
You didn't specify the port.
smtp.Port = 1111; // whatever port your SMTP server uses
The SMTP has three different "standard" ports: 25, 465 and 587. According to msdn documentation, the default value for the Port property is 25.
How to request the operating system to send email with a specific subject, body and attachment? The OS should launch the default email client with the fields pre-loaded?
Specifically what API functions are available in C#.net?
Since you want the outlook to send the email, substitute the port number and host with that of the outlook.
To Open Outlook with pre-loaded fields:
using System.Diagnostics;
// ...
Process.Start(String.Format("mailto:{0}?subject={1}&cc={2}&bcc={3}&body={4}", address, subject, cc, bcc, body))
To send the Email directly :
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);
}
This is a simple adapter for system SmtpClient that will simplify yours tests.
public class SmtpClientAdapter : ISmtpClient
{
private bool disposed;
private SmtpClient smtpClient = new SmtpClient();
public SendResult Send(MailMessage message)
{
if (disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
try
{
smtpClient.Send(message);
return SendResult.Successful;
}
catch (Exception e)
{
return new SendResult(false, e.Message);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
if (smtpClient != null)
{
smtpClient.Dispose();
smtpClient = null;
}
}
disposed = true;
}
}
public class SendResult : SimpleResult
{
public SendResult(bool success, string message)
: base(success, message)
{
}
public static SendResult Successful
{
get
{
return new SendResult(true, string.Empty);
}
}
}
Usage
var emailFrom = new MailAddress(sender);
var emailTo = new MailAddress(recipient);
var mailMessage = new MailMessage(emailFrom, emailTo)
{
Subject = "Subject ",
Body = "Body"
};
using (var client = new SmtpClientAdapter())
{
return client.Send(mailMessage);
}
Here is a simple way to do it,
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);
}
Source : Link
A operating system API function for this isn't avaiable.