منتدى فيجوال بيسك لكل العرب | منتدى المبرمجين العرب

نسخة كاملة : لارسال رسالة الكترونية eMail
أنت حالياً تتصفح نسخة خفيفة من المنتدى . مشاهدة نسخة كاملة مع جميع الأشكال الجمالية .
كاتب الموضوع : Boutemine Oualid


كود :
using System;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Diagnostics;
private String m_Username = String.Empty;
private String m_Password = String.Empty;
private String m_SmtpServer = String.Empty;

/// <summary>
/// Value has been set by default at 25. Default value for SmtpServer
/// </summary>
private int m_Port = 25;


/// <summary>
/// Sends an email with attachment
/// </summary>
/// <param name="_from">person who is sending the mail</param>
/// <param name="_to">person who will receive the mail</param>
/// <param name="_subject">mail subject</param>
/// <param name="_message">mail message</param>
/// <param name="attachment">file that will be attached to the mail</param>
/// <returns>True if mail haas been sent properly. false otherwise</returns>
public Boolean Send(String _from, String _to, String _subject, String _message, String attachment)
{
try {
MailAddress from = new MailAddress(_from);
MailAddress to = new MailAddress(_to);

MailMessage em = new MailMessage(from, to);
//em.CC.Add(); It is also possible to add CC or BCC recipient on that way.
//em.Bcc.Add();
em.BodyEncoding = Encoding.UTF8;
em.IsBodyHtml = true;
em.Subject = _subject;
em.Body = _message;

if(!String.IsNullOrEmpty(attachment))
{
Attachment a = new Attachment(attachment);
em.Attachments.Add(a);
}

return Send(em);
}
catch (Exception exc) {
Trace.WriteLine(String.Format("Email could not be send.", exc));
return false;
}
}

/// <summary>
/// Sends a Mail (MailMessage)
/// </summary>
/// <param name="_message">mail message</param>
/// <returns>True if mail haas been sent properly. false otherwise</returns>
private Boolean Send(MailMessage _message)
{
try {
if(String.IsNullOrEmpty(this.m_SmtpServer))
throw new Exception("SmtpServer must be specified");

SmtpClient client = new SmtpClient(this.m_SmtpServer);
client.Port = this.m_Port;

if (this.m_Username != null && this.m_Password != null) {
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(this.m_Username, this.m_Password);
}

client.Send(_message);
return true;
}
catch (SmtpException exc) {
Trace.WriteLine(String.Format("Email could not be send.", exc));
return false;
}
}