本文整理汇总了C#中System.Net.Mail.SmtpClient.Send方法的典型用法代码示例。如果您正苦于以下问题:C# SmtpClient.Send方法的具体用法?C# SmtpClient.Send怎么用?C# SmtpClient.Send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Mail.SmtpClient
的用法示例。
在下文中一共展示了SmtpClient.Send方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Send
/// <summary>
/// Sends an email
/// </summary>
/// <param name="to">The list of recipients</param>
/// <param name="subject">The subject of the email</param>
/// <param name="body">The body of the email, which may contain HTML</param>
/// <param name="htmlEmail">Should the email be flagged as "html"?</param>
/// <param name="cc">A list of CC recipients</param>
/// <param name="bcc">A list of BCC recipients</param>
public static void Send(List<String> to, String subject, String body, bool htmlEmail = false, List<String> cc = null, List<String> bcc = null)
{
// Need to have at least one address
if (to == null && cc == null && bcc == null)
throw new System.ArgumentNullException("At least one of the address parameters (to, cc and bcc) must be non-null");
NetworkCredential credentials = new NetworkCredential(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.AdminEmail), JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPPassword));
// Set up the built-in MailMessage
MailMessage mm = new MailMessage();
mm.From = new MailAddress(credentials.UserName, "Just Press Play");
if (to != null) foreach (String addr in to) mm.To.Add(new MailAddress(addr, "Test"));
if (cc != null) foreach (String addr in cc) mm.CC.Add(new MailAddress(addr));
if (bcc != null) foreach (String addr in bcc) mm.Bcc.Add(new MailAddress(addr));
mm.Subject = subject;
mm.IsBodyHtml = htmlEmail;
mm.Body = body;
mm.Priority = MailPriority.Normal;
// Set up the server communication
SmtpClient client = new SmtpClient
{
Host = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPServer),
Port = int.Parse(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPPort)),
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = credentials
};
client.Send(mm);
}
示例2: EmailConfirmations
private void EmailConfirmations(CheckoutViewModel checkout)
{
var fromBody = string.Format("from {0} {1} at {2}", checkout.FirstName, checkout.LastName, checkout.Email);
var settings = GetEmailSettings();
using (
var client = new SmtpClient(settings.Server, settings.Port)
{
Credentials = new NetworkCredential(settings.Username, settings.Password),
EnableSsl = settings.EnableSsl
})
{
if (!string.IsNullOrEmpty(checkout.Money))
{
client.Send(settings.From, settings.Money, "New Money Gift", string.Format("${0} {1}", checkout.Money, fromBody));
}
if (!string.IsNullOrEmpty(checkout.Time))
{
client.Send(settings.From, settings.Time, "New Time Gift", string.Format("{0} hours {1}", checkout.Time, fromBody));
}
if (!string.IsNullOrEmpty(checkout.Talent))
{
client.Send(settings.From, settings.Talent, "New Talent Gift", string.Format("{0} talent {1}", checkout.Talent, fromBody));
}
if (!string.IsNullOrEmpty(checkout.InKind))
{
client.Send(settings.From, settings.Time, "New In Kind Gift", string.Format("{0} in kind {1}", checkout.InKind, fromBody));
}
client.Send(settings.From, checkout.Email, settings.Subject, settings.Body);
}
}
示例3: button1_Click
private void button1_Click(object sender, EventArgs e)
{
try
{
mail = new MailMessage();
SmtpServer = new SmtpClient("smtp.yourdomain.com");
mail.From = new MailAddress("[email protected]");
mail.To.Add(combo.Items[combo.SelectedIndex].ToString());
mail.Subject = subjbox.Text.ToString();
mail.Body = msgbox.Text.ToString();
if (strFileName != string.Empty)
{
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(strFileName);
mail.Attachments.Add(attachment);
SmtpServer.Send(mail);
MessageBox.Show("Sent Message With Attachment", "MMS by Paul");
}
else {
SmtpServer.Send(mail);
MessageBox.Show("Sent Message", "MMS by Paul");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
示例4: Send
public void Send(string @from, string to, string subject, string body, Stream stream = null,
string attachmentMimeType = null)
{
using (var client = new SmtpClient())
{
if (stream == null || attachmentMimeType == null)
{
client.Send(@from, to, subject, body);
}
else
{
if (string.IsNullOrEmpty(attachmentMimeType))
{
throw new ArgumentNullException();
}
//message
var mailMessage = new MailMessage(@from, to, subject, body);
//attachment
var attachment = new Attachment(stream, new ContentType(attachmentMimeType));
var disposition = attachment.ContentDisposition;
// Suggest a file name for the attachment.
disposition.FileName = ATTACHMENT_NAME;
// Add the attachment to the message.
mailMessage.Attachments.Add(attachment);
client.Send(mailMessage);
}
}
}
示例5: ConfirmOrder
public void ConfirmOrder(Order order)
{
if (order.Status != OrderStatus.Draft)
{
throw new InvalidOperationException("Only draft orders can be confirmed");
}
order.Status = OrderStatus.ReadyToShip;
var smtpClient = new SmtpClient();
// these emails would be much longer in practice and probably not hard coded!
var confirmationEmail = new MailMessage(
"[email protected]",
order.Customer.Email,
"Order confirmation: " + order.Code,
"Hello there, Your order is confirmed and has gone off for processing");
smtpClient.Send(confirmationEmail);
var shipmentRequestEmail = new MailMessage(
"[email protected]",
OrderFulfilmentEmailAddress,
"Order shipment request: " + order.Code,
"Hello there, this order is confirmed. Please arrange shipment.");
smtpClient.Send(shipmentRequestEmail);
// maybe save order here as this would be typical procedural style (i.e. no persistence ignorance)
}
示例6: SendNotification
public void SendNotification(Notification notification, string message, ref string strError)
{
try
{
string email = string.Empty;
string password = string.Empty;
if (email == string.Empty || password == string.Empty)
throw new Exception("The email and password are not set for notifications");
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential(email, password),
EnableSsl = true
};
if (notification.NotificationType.ToUpper() == "EMAIL")
client.Send(email, notification.EmailAddress, "CryptoCoinControl Price Notification", message);
else if (notification.NotificationType.ToUpper() == "SMS")
client.Send(email, notification.PhoneNumber + notification.CarrierGateway, string.Empty, message);
}
catch (Exception ex)
{
strError = ex.Message;
}
}
示例7: SendEmail
public static void SendEmail(EmailSenderData emailData)
{
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient(emailData.SmtpClient);
smtpServer.Port = 25;
mail.From = new MailAddress(emailData.FromEmail);
foreach (string currentEmail in emailData.Emails)
{
mail.To.Add(currentEmail);
}
mail.Subject = emailData.Subject;
mail.IsBodyHtml = true;
mail.Body = emailData.EmailBody;
if (emailData.AttachmentPath != null)
{
foreach (string currentPath in emailData.AttachmentPath)
{
Attachment attachment = new Attachment(currentPath);
mail.Attachments.Add(attachment);
}
smtpServer.Send(mail);
DisposeAllAttachments(mail);
}
else
{
smtpServer.Send(mail);
}
mail.Dispose();
smtpServer.Dispose();
}
示例8: EmailSend
public string EmailSend(StreamReader sr)
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(sr.ReadToEnd());
XmlNode root = xDoc.DocumentElement;
XmlNode emailNode = root.SelectSingleNode("EMAILID");
XmlNode contactnumberNode = root.SelectSingleNode("CONTACTNUMBER");
XmlNode messageNode = root.SelectSingleNode("MESSAGE");
string emailId = (emailNode.InnerText);
string contactnumber = (contactnumberNode.InnerText);
string message = (messageNode.InnerText);
var fromaddress = new MailAddress("[email protected]");
var frompass = "techgeek786";
var clientAdress = new MailAddress(emailId.ToString());
var toAdress = new MailAddress("[email protected]");
string subject = "Contact Mail from" + emailId;
string body = "Message: " + message + "\n Contact Number: " + contactnumber + "\n from: <" + emailId + ">";
string Usersubject = "Success Message";
string Userbody = "Successfully Send message to TechGeek.org.in \n we will contact you as soon as possible \n Thanks.";
try
{
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromaddress.Address, frompass)
};
using (var clientMessage = new MailMessage(fromaddress, clientAdress)
{
Subject = Usersubject,
Body = Userbody
})
smtp.Send(clientMessage);
using (var Message = new MailMessage(fromaddress, toAdress)
{
Subject = subject,
Body = body
})
smtp.Send(Message);
return "Send Data Successfully";
}
catch (Exception ex)
{
return ("Error" + ex.Message);
}
}
示例9: SendEmail
public void SendEmail(long batchControlLogID, string errorMessage)
{
if (logger.IsDebugEnabled)
{
logger.Debug(string.Format("SendEmail({0},{1}", batchControlLogID, errorMessage));
}
if (!this.DoSendEmail)
{
return;
}
ArgumentCheck.ArgumentNullOrEmptyCheck(this.EmailRecipients, Constants.ERRORMESSAGE_EMAILRECIPIENTS);
ArgumentCheck.ArgumentNullOrEmptyCheck(this.EmailSender, Constants.ERRORMESSAGE_EMAILSENDER);
////ArgumentCheck.ArgumentNullOrEmptyCheck(this.SMTPDomain, Constants.ERRORMESSAGE_SMTPDOMAIN);
////ArgumentCheck.ArgumentNullOrEmptyCheck(this.SMTPUser, Constants.ERRORMESSAGE_SMTPUSER);
ArgumentCheck.ArgumentNullOrEmptyCheck(this.SMTPPort, Constants.ERRORMESSAGE_SMTPPORT);
ArgumentCheck.ArgumentNullOrEmptyCheck(this.SMTPServer, Constants.ERRORMESSAGE_SMTPSERVER);
try
{
string errorSubject = null;
string errorBody = null;
if (!string.IsNullOrEmpty(errorMessage))
{
errorSubject = "Error Processing Payments ";
errorBody = errorMessage;
}
else if (batchControlLogID > 0)
{
errorSubject = "Error Processing Payments, Batch ID: " + batchControlLogID.ToString();
errorBody = errorSubject;
}
MailMessage mail = new MailMessage(this.EmailSender, this.EmailRecipients, errorSubject, errorBody);
SmtpClient smtpClient = new SmtpClient(this.SMTPServer, this.SMTPPort);
smtpClient.UseDefaultCredentials = true;
if (string.IsNullOrEmpty(this.SMTPEncryptedPassword) || string.IsNullOrEmpty(this.SMTPDomain) || string.IsNullOrEmpty(this.SMTPUser))
{
smtpClient.Send(mail);
}
else
{
string password = this.SMTPEncryptedPassword; // Decryptor.DecryptPassword(this.SMTPEncryptedPassword);
ImpersonateUser impersonateUser = new ImpersonateUser();
WindowsImpersonationContext impersonatedUser = impersonateUser.SetImpersonatedUser(this.SMTPUser, this.SMTPDomain, password);
{
smtpClient.Send(mail);
}
}
}
catch (Exception ex)
{
logger.Error(string.Format("SendEmail - {0}", ex.Message));
}
}
示例10: sendMail
public string sendMail(string userdisplayname, string to, string from, string subject, string msg, string path)
{
string str = "";
SmtpClient client = new SmtpClient
{
Credentials = new NetworkCredential(username, passwd),
Port = port,
Host = hostname,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Timeout = 20000
};
this.mail = new MailMessage();
string[] strArray = to.Split(new char[] { ',' });
try
{
this.mail.From = new MailAddress(from, userdisplayname, Encoding.UTF8);
for (byte i = 0; i < strArray.Length; i = (byte)(i + 1))
{
this.mail.To.Add(strArray[i]);
}
this.mail.Priority = MailPriority.High;
this.mail.Subject = subject;
this.mail.Body = msg;
if (path != "")
{
LinkedResource item = new LinkedResource(path)
{
ContentId = "Logo"
};
AlternateView view = AlternateView.CreateAlternateViewFromString("<html><body><table border=2><tr width=100%><td><img src=cid:Logo alt=companyname /></td><td>FROM BLUEFROST</td></tr></table><hr/></body></html>" + msg, null, "text/html");
view.LinkedResources.Add(item);
this.mail.AlternateViews.Add(view);
this.mail.IsBodyHtml = true;
this.mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
this.mail.ReplyTo = new MailAddress(to);
client.Send(this.mail);
return str;
}
if (path == "")
{
this.mail.IsBodyHtml = true;
this.mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
this.mail.ReplyTo = new MailAddress(to);
client.Send(this.mail);
str = "good";
}
}
catch (Exception exception)
{
if (exception.ToString() == "The operation has timed out")
{
client.Send(this.mail);
str = "bad";
}
}
return str;
}
示例11: Page_Load
private void Page_Load(object sender, System.EventArgs e)
{
MailMessage sprocketToolsMessage = new MailMessage();
sprocketToolsMessage.Subject = "Transaction email";
sprocketToolsMessage.Body = "Test Transaction Email!";
// Step 1a: Modify the POST string.
string formPostData = "cmd = _notify-validate";
foreach (String postKey in Request.Form)
{
string postValue = Encode(Request.Form[postKey]);
formPostData += string.Format("&{0}={1}", postKey, postValue);
sprocketToolsMessage.Body += (postKey + " : " + Request.Form[postKey] + System.Environment.NewLine);
}
// Step 1b: POST the data back to PayPal.
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] postByteArray = Encoding.ASCII.GetBytes(formPostData);
byte[] responseArray = client.UploadData("https://www.paypal.com/cgi-bin/webscr", "POST", postByteArray);
string response = Encoding.ASCII.GetString(responseArray);
//message.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient();
sprocketToolsMessage.From = new MailAddress("[email protected]");
sprocketToolsMessage.To.Add("[email protected]");
// Step 1c: Process the response from PayPal.
switch (response)
{
case "VERIFIED":
{
// Perform steps 2-5 above.
// Continue with automation processing if all steps succeeded.
sprocketToolsMessage.Subject += " VERIFIED";
MailMessage customerEmail = new MailMessage();
customerEmail.IsBodyHtml = true;
customerEmail.Subject = "Sprocket Tools Order - " + Request.Form["txn_id"];
customerEmail.Body = "Thank you for your order!<br/><br/> Please use the attachment to install your copy of " + Request.Form["item_name"];
FileStream fs = new FileStream(WSPMod.GetKeyedWsp(@"SprocketValidator.wsp", Request.Form["address_name"], "*", DateTime.Now.AddYears(100)), FileMode.Open);
Attachment a = new Attachment(fs,"SprocketValidator.wsp");
customerEmail.Attachments.Add(a);
smtpClient.Send(customerEmail);
break
;
}
default:
{
// Possible fraud. Log for investigation.
sprocketToolsMessage.Subject += " FRAUD";
break;
}
}
smtpClient.Send(sprocketToolsMessage);
}
示例12: Submit
public static ReturnObject Submit(HttpContext context, string name, string email, string subject, string message)
{
var sb = new System.Text.StringBuilder();
sb.AppendLine("<html><body>");
sb.AppendLine("<b>Name</b>: " + name + "<br />");
sb.AppendLine("<b>Email</b>: " + email + "<br />");
sb.AppendLine("<b>Subject</b>: " + subject + "<br />");
sb.AppendLine("<b>Message</b>:<br />" + message + "<br />");
sb.AppendLine("</body></html>");
//var msg = new System.Net.Mail.MailMessage("[email protected]", "[email protected]");
var msg = new System.Net.Mail.MailMessage("[email protected]", "[email protected]");
//var msg = new System.Net.Mail.MailMessage("[email protected]", "[email protected]");
msg.IsBodyHtml = true;
msg.Subject = "Contact Message from REMSLogic Webite";
msg.Body = sb.ToString();
var client = new System.Net.Mail.SmtpClient("relay-hosting.secureserver.net");
//var client = new System.Net.Mail.SmtpClient("smtpout.secureserver.net");
//client.Credentials = new System.Net.NetworkCredential("[email protected]", "Safety1");
//client.EnableSsl = false;
client.Send(msg);
sb = new System.Text.StringBuilder();
sb.AppendLine("<html><body>");
sb.AppendLine("Dear " + name + ",<br /><br />");
sb.AppendLine("Thank you for your interest and for contacting us.<br /><br />");
sb.AppendLine("<b>We will respond as soon as possible.</b><br />This website is in final development stages.<br /><br />");
sb.AppendLine("</body></html>");
msg = new System.Net.Mail.MailMessage("[email protected]", email);
msg.IsBodyHtml = true;
msg.Subject = "Thank you for contacting REMSLogic";
msg.Body = sb.ToString();
client.Send(msg);
var ret = new ReturnObject()
{
Error = false,
StatusCode = 200,
Message = "Message sent successfully"
};
return ret;
}
示例13: Send_with_Auth_Success_Test
public void Send_with_Auth_Success_Test()
{
using (var server = new SmtpServerForUnitTest(
address: IPAddress.Loopback,
port: 2525,
credentials: new[] { new NetworkCredential("[email protected]", "[email protected]$$w0rd") }))
{
server.Start();
var client = new SmtpClient("localhost", 2525);
client.Credentials = new NetworkCredential("[email protected]", "[email protected]$$w0rd");
client.Send(
"[email protected]",
"[email protected],[email protected]",
"[HELLO WORLD]",
"Hello, World.");
server.ReceivedMessages.Count().Is(1);
var msg = server.ReceivedMessages.Single();
msg.MailFrom.Is("<[email protected]>");
msg.RcptTo.OrderBy(_ => _).Is("<[email protected]>", "<[email protected]>");
msg.From.Address.Is("[email protected]");
msg.To.Select(_ => _.Address).OrderBy(_ => _).Is("[email protected]", "[email protected]");
msg.CC.Count().Is(0);
msg.Subject.Is("[HELLO WORLD]");
msg.Body.Is("Hello, World.");
}
}
示例14: SendMail
static void SendMail(
string _receivers,
string subject, string content, string attachments)
{
string[] receivers = _receivers.Split(';');
string sender = "[email protected]";
MailMessage msg = new MailMessage(sender, receivers[0])
{
Body = content,
BodyEncoding = Encoding.UTF8,
IsBodyHtml = false,
Priority = MailPriority.Normal,
ReplyTo = new MailAddress(sender),
Sender = new MailAddress(sender),
Subject = subject,
SubjectEncoding = Encoding.UTF8,
};
for (int i = 1; i < receivers.Length; ++i) msg.CC.Add(receivers[i]);
if (!string.IsNullOrEmpty(attachments))
{
foreach (var fileName in attachments.Split(';'))
{
msg.Attachments.Add(new Attachment(fileName));
}
}
SmtpClient client = new SmtpClient("smtp.126.com", 25)
{
Credentials = new System.Net.NetworkCredential("testuser", "123456"),
EnableSsl = true,
};
client.Send(msg);
}
示例15: Send
public void Send(SPWeb web, IEnumerable<string> emailTo, string senderDisplayName, string subject, string body)
{
if (web == null) throw new ArgumentNullException("web");
if (emailTo == null || !emailTo.Any()) throw new ArgumentNullException("emailTo");
var webApplication = web.Site.WebApplication;
var from = new MailAddress(webApplication.OutboundMailSenderAddress, senderDisplayName);
var message = new MailMessage
{
IsBodyHtml = true,
Body = body,
From = from
};
var smtpServer = webApplication.OutboundMailServiceInstance;
var smtp = new SmtpClient(smtpServer.Server.Address);
foreach (var email in emailTo)
{
message.To.Add(email);
}
message.Subject = subject;
smtp.Send(message);
}