本文整理汇总了C#中SmtpClient.SendAsync方法的典型用法代码示例。如果您正苦于以下问题:C# SmtpClient.SendAsync方法的具体用法?C# SmtpClient.SendAsync怎么用?C# SmtpClient.SendAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SmtpClient
的用法示例。
在下文中一共展示了SmtpClient.SendAsync方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendAsync
/// <summary>
/// A MailMessage extension method that sends this message asynchronous.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="userToken">The user token.</param>
public static void SendAsync(this MailMessage @this, object userToken)
{
using (var smtpClient = new SmtpClient())
{
smtpClient.SendAsync(@this, userToken);
}
}
示例2: SendEmail
public void SendEmail(string name, string from, string company, string phone, string comments)
{
MailMessage mm = new MailMessage(from, "[email protected]", "[Sons of Suns Contact Form]",
String.Format("{0} : {1} {2} {3}", name, company, phone, comments));
SmtpClient client = new SmtpClient();
//client.EnableSsl = true;
try
{
client.SendAsync(mm, null);
}
catch (SmtpException)
{
throw;
}
catch (Exception)
{
throw;
}
//client.Send(mm);
//mm.Dispose();
client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
}
示例3: SubmitButton_Click
protected void SubmitButton_Click(object sender, EventArgs e)
{
ContactUsMultiView.ActiveViewIndex = 1;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(String.Format("FROM: {0}\r\n", NameTextBox.Text));
sb.Append(String.Format("PHONE OR EMAIL: {0}\r\n", PhoneOrEmailTextBox.Text));
sb.Append(String.Format("SUBJECT: {0}\r\n", SubjectTextBox.Text));
sb.Append(String.Format("MESSAGE:\r\n{0}", MessageTextBox.Text));
MailMessage msg = new MailMessage("[email protected]", "[email protected]", String.Format("Contact Us Form. From: {0} Subject: {1}", NameTextBox.Text, SubjectTextBox.Text), sb.ToString());
SmtpClient smtp = new SmtpClient();
smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_SendCompleted);
try
{
smtp.SendAsync(msg, msg);
}
catch (SmtpException ex)
{
SmtpConfirmationLabel.Text = "SmtpException: " + ex.Message + "<br />Source: " + ex.Source + "<br />Stack Trace: " + ex.StackTrace + "<br />Status Code from SMTP Server: " + ex.StatusCode;
}
catch (Exception ex)
{
SmtpConfirmationLabel.Text = "Exception: " + ex.Message + "<br />Source: " + ex.Source + "<br />Stack Trace: " + ex.StackTrace;
}
//smtp.Send(msg);
}
示例4: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
MailMessage m = new MailMessage("[email protected]", "[email protected]", "Stapler", "I believe you have my stapler.");
SmtpClient sc = new SmtpClient();
sc.SendCompleted += new SendCompletedEventHandler(MailSendCompleted);
sc.SendAsync(m, m);
}
示例5: SendMailAsync
public static void SendMailAsync(object mailMessage)
{
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
var credentials = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
var smtpClient = new SmtpClient()
{
UseDefaultCredentials = false,
Credentials = credentials
};
smtpClient.SendAsync((MailMessage)mailMessage, null);
}
示例6: SendAsync
/// <summary>
/// A MailMessage extension method that sends this message asynchronous.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="userToken">The user token.</param>
/// <example>
/// <code>
/// using System.Net.Mail;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Net_Mail_MailMessage_SendAsync
/// {
/// [TestMethod]
/// public void SendAsync()
/// {
/// var token = new object();
///
/// // Type
/// var @this = new MailMessage("[email protected]", "[email protected]", "Fizz", "Buzz");
///
/// // Examples
/// @this.SendAsync(token); // Send a mail async
/// }
/// }
/// }
/// </code>
/// </example>
public static void SendAsync(this MailMessage @this, object userToken)
{
#if (NET35 || NET3 || NET2)
var smtpClient = new SmtpClient();
smtpClient.SendAsync(@this, userToken);
smtpClient = null;
#else
using (var smtpClient = new SmtpClient()) {
smtpClient.SendAsync(@this, userToken);
}
#endif
}
示例7: RunSendEmail
public void RunSendEmail()
{
//Mail 內容設定
MailMessage message = new MailMessage(new MailAddress("[email protected]", "苏州电博会"), new MailAddress(receiverAddress, ""));//MailMessage(寄信者, 收信者)
message.SubjectEncoding = Encoding.UTF8; //標題編碼
message.BodyEncoding = Encoding.UTF8; //內容編碼
switch (GameManager.script.語言版本)
{
case GameManager.Language.簡體:
message.Subject = "现代郎世宁-百骏图"; //E-mail主旨
message.Body = "感谢使用现代郎世宁-百骏图,附件为您设计的百骏图"; //E-mail內容
break;
case GameManager.Language.繁體:
message.Subject = "現代郎世寧-百駿圖"; //E-mail主旨
message.Body = "感謝使用現代郎世寧-百駿圖,附件為您設計的百駿圖"; //E-mail內容
break;
default:
break;
}
Attachment attachment = new Attachment(ScreenShot.script.imagePath);//<-這是附件部分~先用附件的物件把路徑指定進去~
message.Attachments.Add(attachment);//<-郵件訊息中加入附件
//mail server 內容設定
SmtpClient smtpClient;
smtpClient = new SmtpClient("mail.goemex.biz", 25); //gmail smtp設定 port:587 SMTP: smtp.gmail.com
smtpClient.Credentials = (ICredentialsByHost)new NetworkCredential("[email protected]", "359359");//gmail 帳密 "[email protected]", "hahamiror123"
//smtpClient.EnableSsl = false;//打開ssl
//設定安全機制(必須設定否則無法發送)
//ServicePointManager.ServerCertificateValidationCallback =
// delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
// { return true; };
//完成寄信後的callback function
smtpClient.SendCompleted += this.smtp_SendCompleted;
//寄送mail
smtpClient.SendAsync(message, "Send");//寄送
this.UIEnable = false;
}
示例8: SendBulkMail
private static void SendBulkMail(string messageTemplateFileName, Dictionary<string, string> keysValuePairCollection, List<string> mailList, string subject, string replyTo = "")
{
// create message body
string templatePath = HttpContext.Current.Server.MapPath("~/App_Data/MailTemplates/" + messageTemplateFileName);
if (!File.Exists(templatePath))
{
throw new FileNotFoundException("Message Template File Not Found");
}
StringBuilder sbTemplate = new StringBuilder(File.ReadAllText(templatePath));
string key = string.Empty;
foreach (KeyValuePair<string, string> keyValuePair in keysValuePairCollection)
{
key = "#" + keyValuePair.Key + "#";
if (!sbTemplate.ToString().Contains(key))
throw new System.Exception(string.Format("this key - {0} - does not exist in the current template", key));
sbTemplate = sbTemplate.Replace(key, keyValuePair.Value);
}
// send bulk email
System.Net.Mail.SmtpClient smtpClient = null;
//NetworkCredential mailAuthentication = new NetworkCredential(FromAddress, FromPassword);
MailMessage mailMessage = null;
Object state = null;
foreach (string toAddress in mailList)
{
mailMessage = new MailMessage();
mailMessage.From = new MailAddress(WebConfigurationManager.AppSettings["FromEmail"]);
mailMessage.To.Add(toAddress);
mailMessage.Subject = subject;
mailMessage.Body = sbTemplate.ToString();
mailMessage.IsBodyHtml = true;
if (!string.IsNullOrEmpty(replyTo))
{
mailMessage.ReplyToList.Add(replyTo);
}
//smtpClient = new System.Net.Mail.SmtpClient(SmptServer, SmtpPort);
smtpClient = new SmtpClient();
state = mailMessage;
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
//Enable SSL
//smtpClient.EnableSsl = true;
//smtpClient.UseDefaultCredentials = false;
//smtpClient.Credentials = mailAuthentication;
// Send
smtpClient.SendAsync(mailMessage, state);
}
}
示例9: SendMail
//发送邮件
public static void SendMail(MailMessage message)
{
message.From = new MailAddress(ConfigurationManager.AppSettings["MailAccount"], "软件学院自主学习平台邮推服务小机器人");
message.BodyEncoding = System.Text.Encoding.Default;
message.SubjectEncoding = System.Text.Encoding.Default;
message.Priority = MailPriority.High;
message.IsBodyHtml = false;
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["MailServer"]);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
//身份认证
client.Credentials = new
System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailAccount"], ConfigurationManager.AppSettings["MailPassword"]);
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
try
{
client.SendAsync(message, "推送");
}
catch { }
}
示例10: SmtpSendButton_Click
/// <summary>
/// Send an email using the SMTP settings specified.
/// </summary>
private async void SmtpSendButton_Click(object sender, EventArgs e)
{
X509Certificate2 signingCertificate = null;
if (SmtpSmimeSign.Checked || SmtpSmimeTripleWrap.Checked)
{
// If S/MIME signing the message, attempt to look up a certificate from the Windows certificate store.
if (SmtpSmimeSerialNumber.Text.Length > 0)
{
// Try looking the certificate up by its serial number, falling back to finding it by its subject name.
signingCertificate = CertHelper.GetCertificateBySerialNumber(StoreLocation.CurrentUser, SmtpSmimeSerialNumber.Text);
if (signingCertificate == null)
signingCertificate = CertHelper.GetCertificateBySerialNumber(StoreLocation.LocalMachine, SmtpSmimeSerialNumber.Text);
if (signingCertificate == null)
signingCertificate = CertHelper.GetCertificateBySubjectName(StoreLocation.CurrentUser, SmtpSmimeSerialNumber.Text);
if (signingCertificate == null)
signingCertificate = CertHelper.GetCertificateBySubjectName(StoreLocation.LocalMachine, SmtpSmimeSerialNumber.Text);
}
if (signingCertificate == null)
{
// Check if there's a matching certificate based on the sender's address.
signingCertificate = CertHelper.GetCertificateBySubjectName(StoreLocation.CurrentUser, SmtpFrom.Text);
if (signingCertificate == null)
signingCertificate = CertHelper.GetCertificateBySubjectName(StoreLocation.LocalMachine, SmtpFrom.Text);
}
if (signingCertificate == null)
{
MessageBox.Show("Certificate not found.");
SmtpSmimeSerialNumber.Focus();
return;
}
}
try
{
int smtpPort = 25;
int.TryParse(SmtpPort.Text, out smtpPort);
SmtpClient smtpClient = new SmtpClient(SmtpHost.Text, smtpPort);
smtpClient.Credentials = new NetworkCredential(SmtpUsername.Text, SmtpPassword.Text);
smtpClient.EnableSsl = true;
MailMessage message = new MailMessage();
message.From = new MailAddress(SmtpFrom.Text);
// Parse all addresses provided into MailAddress objects.
if (SmtpTo.Text.Length > 0)
{
MailAddressCollection toAddresses = MailAddressCollection.Parse(SmtpTo.Text);
foreach (MailAddress toAddress in toAddresses)
message.To.Add(toAddress);
}
if (SmtpCC.Text.Length > 0)
{
MailAddressCollection ccAddresses = MailAddressCollection.Parse(SmtpCC.Text);
foreach (MailAddress ccAddress in ccAddresses)
message.CC.Add(ccAddress);
}
if (SmtpBcc.Text.Length > 0)
{
MailAddressCollection bccAddresses = MailAddressCollection.Parse(SmtpBcc.Text);
foreach (MailAddress bccAddress in bccAddresses)
message.Bcc.Add(bccAddress);
}
message.Subject = SmtpSubject.Text;
message.Body = SmtpBody.Text;
// Process attachments.
string[] attachmentLines = SmtpAttachments.Text.Replace("\r", "").Split('\n');
foreach (string attachmentLine in attachmentLines)
{
if (attachmentLine.Trim().Length > 0)
message.Attachments.Add(new Attachment(attachmentLine.Trim()));
}
message.IsBodyHtml = SmtpIsHtml.Checked;
message.SmimeSigningCertificate = signingCertificate;
message.SmimeSigned = SmtpSmimeSign.Checked;
message.SmimeEncryptedEnvelope = SmtpSmimeEncrypt.Checked;
message.SmimeTripleWrapped = SmtpSmimeTripleWrap.Checked;
await smtpClient.SendAsync(message);
MessageBox.Show("Message successfully sent.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("SMTP send exception:\r\n\r\n" + ex.Message, "SMTP send exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
示例11: Send_Email
private void Send_Email(string SenderName, string SenderEmailId, string ReceiverEmailId, string Subject, string Content, bool IsHTMLBody = false, string ReceiverName = "", string RegisterationOrSubscriptionId = "", string RegisterationOrSubscription = "")
{
MailMessage MailMessage;
SmtpClient SmtpClient;
System.Net.Mail.MailAddress ToAddress = new MailAddress(ReceiverEmailId, ReceiverName);
try
{
MailMessage = new MailMessage();
SmtpClient = new SmtpClient();
MailMessage.From = new MailAddress(SenderEmailId, SenderName);
MailMessage.To.Add(ToAddress);
MailMessage.IsBodyHtml = IsHTMLBody;
MailMessage.Priority = MailPriority.Normal;
MailMessage.Subject = Subject;
MailMessage.Body = Content;
SmtpClient.ServicePoint.MaxIdleTime = 2;
SmtpClient.SendCompleted += new SendCompletedEventHandler((sender, e) => SendCompletedCallback(sender, e, RegisterationOrSubscriptionId, RegisterationOrSubscription));
SmtpClient.SendAsync(MailMessage, null);
// MailMessage.Dispose();
}
catch (Exception ex)
{
Global.CreateExceptionString(ex, null);
}
finally
{
}
}
示例12: SendMail
public void SendMail()
{
try
{
_mailMessage = new MailMessage(_mailFrom, _mailTo);
if (!string.IsNullOrEmpty(_mailCC)) { _mailMessage.CC.Add(_mailCC); }
if (!string.IsNullOrEmpty(_mailBCC)) { _mailMessage.Bcc.Add(_mailBCC); }
_mailMessage.Subject = _mailSubject;
_mailMessage.Body = _mailBody;
_mailMessage.IsBodyHtml = _bIsBodyHtml;
if (!string.IsNullOrEmpty(_fileNameToAttach))
{
string strFileName = HttpContext.Current.Request.PhysicalApplicationPath.ToString() + "\\NewsLetters\\" + _fileNameToAttach;
Attachment itm = new Attachment(strFileName);
_mailMessage.Attachments.Add(itm);
}
//string strSMTPServer = System.Configuration.ConfigurationManager.AppSettings["SMTPSERVER"].ToString();
//_smptpClient = new SmtpClient(strSMTPServer);
_smptpClient = new SmtpClient();
if (SmtpSelected == (int)SmtpServers.AmazonAws || SmtpSelected == -1)
{
_smptpClient.Host = strAmazonServer;
_smptpClient.EnableSsl = true;
_smptpClient.Port = iPort;
_smptpClient.Credentials = new System.Net.NetworkCredential(strAmazonUserName, strAmazonPassword);
}
else if (SmtpSelected == (int)SmtpServers.BeastTest)
{
_smptpClient.Host = System.Configuration.ConfigurationManager.AppSettings["SMTP_BeastTest"];
}
else if (SmtpSelected == (int)SmtpServers.BeastDemo)
{
_smptpClient.Host = System.Configuration.ConfigurationManager.AppSettings["SMTP_BeastDemo"];
}
if (_bSendAsync)
{
_smptpClient.SendCompleted += new SendCompletedEventHandler(_smptpClient_SendCompleted);
_smptpClient.SendAsync(_mailMessage, "VCMmail");
}
else
{
_smptpClient.Send(_mailMessage);
}
}
catch (Exception ex)
{
LogUtility.Error("VCM_Mail.cs", "SendMail()", ex.Message, ex);
throw;
}
finally
{
_mailMessage = null;
_smptpClient = null;
}
}
示例13: SendMail
public static void SendMail(MailAddress From, MailAddress[] To, String subject, String body, MailAddress[] CC, MailAddress[] BCC, string[] Attachments)
{
try
{
MailMessage message = new MailMessage();
message.From = From;
// Add To
foreach (MailAddress a in To)
{
message.To.Add(a);
}
// Add CC
if (CC != null)
{
foreach (MailAddress a in CC)
{
message.CC.Add(a);
}
}
// Add BCC
if (BCC != null)
{
foreach (MailAddress a in BCC)
{
message.Bcc.Add(a);
}
}
if (Attachments != null)
{
foreach (string a in Attachments)
{
message.Attachments.Add(new Attachment(File.OpenRead(a), Path.GetFileName(a)));
}
}
message.Subject = subject;
message.Body = body;
SmtpClient smtp = new SmtpClient();
smtp.SendCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
System.Diagnostics.Trace.TraceError(e.Error.ToString());
}
MailMessage userMessage = e.UserState as MailMessage;
if (userMessage != null)
{
userMessage.Dispose();
}
};
smtp.SendAsync(message, message);
}
catch (SmtpException smtpEx)
{
System.Diagnostics.Trace.TraceError(smtpEx.ToString());
}
}