سؤال

بدلاً من الاعتماد على مضيفي لإرسال البريد الإلكتروني، كنت أفكر في إرسال رسائل البريد الإلكتروني باستخدام حساب Gmail الخاص بي.رسائل البريد الإلكتروني عبارة عن رسائل بريد إلكتروني مخصصة للفرق التي أعزفها في العرض الخاص بي.هل من الممكن أن تفعل؟

هل كانت مفيدة؟

المحلول

تأكد من الاستخدام System.Net.Mail, ، وليس المهمل System.Web.Mail.القيام بـ SSL مع System.Web.Mail عبارة عن فوضى عارمة من الإضافات المتسللة.

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);
}

نصائح أخرى

الإجابة أعلاه لا تعمل.عليك أن تحدد DeliveryMethod = SmtpDeliveryMethod.Network أو سيعود ب"لم تتم مصادقة العميل" خطأ.كما أنه من الجيد دائمًا تخصيص مهلة.

الكود المنقح:

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);
}

لكي تعمل الإجابات الأخرى "من الخادم" أولاً قم بتشغيل الوصول للتطبيقات الأقل أمانًا في حساب جوجل.

يبدو أن Google قد غيرت سياستها الأمنية مؤخرًا.لم تعد الإجابة ذات التقييم الأعلى تعمل، حتى تقوم بتغيير إعدادات حسابك كما هو موضح هنا: https://support.google.com/accounts/answer/6010255?hl=ar-GBenter image description here

enter image description here

اعتبارًا من مارس 2016، قامت جوجل بتغيير موقع الإعداد مرة أخرى!

هذا لإرسال البريد الإلكتروني مع المرفقات.بسيطة وقصيرة..

مصدر: 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 محاولات تسجيل الدخول من بعض التطبيقات أو الأجهزة التي لا تستخدم معايير الأمان الحديثة.ونظرًا لسهولة اختراق هذه التطبيقات والأجهزة، فإن حظرها يساعد في الحفاظ على أمان حسابك.

تتضمن بعض أمثلة التطبيقات التي لا تدعم أحدث معايير الأمان ما يلي:

  • تطبيق البريد على جهاز iPhone أو iPad الذي يعمل بنظام iOS 6 أو أقل
  • تطبيق البريد على هاتف Windows الخاص بك الذي يسبق الإصدار 8.1
  • بعض برامج بريد سطح المكتب مثل Microsoft Outlook وMozilla Thunderbird

ولذلك، عليك تمكين تسجيل دخول أقل أمانًا في حساب جوجل الخاص بك.

بعد تسجيل الدخول إلى حساب جوجل اذهب إلى:

https://myaccount.google.com/lesssecureapps
أو
https://www.google.com/settings/security/lesssecureapps

في لغة #C يمكنك استخدام الكود التالي:

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);
    }
}

هنا هو الإصدار الخاص بي:"إرسال البريد الإلكتروني في C # باستخدام 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();
     }
    }
   }
 }

لكي أتمكن من تشغيله، كان عليّ تمكين حساب Gmail الخاص بي مما يتيح للتطبيقات الأخرى الوصول إليه.ويتم ذلك من خلال "تمكين التطبيقات الأقل أمانًا" و أيضًا باستخدام هذا الرابط:https://accounts.google.com/b/0/DisplayUnlockCaptcha

آمل أن يعمل هذا الرمز بشكل جيد.يمكنك المحاولة.

// 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);

تضمين هذا،

using System.Net.Mail;

وثم،

MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); 
SmtpClient client = new SmtpClient("smtp.gmail.com");

client.Port = Convert.ToInt16("587");
client.Credentials = new System.Net.NetworkCredential("mail-id@gmail.com","password");
client.EnableSsl = true;

client.Send(sendmsg);

مصدر : إرسال البريد الإلكتروني في ASP.NET C#

يوجد أدناه نموذج لرمز عمل لإرسال بريد باستخدام لغة C#، وفي المثال أدناه أستخدم خادم SMTP الخاص بشركة Google.

الكود واضح بذاته، استبدل البريد الإلكتروني وكلمة المرور بقيم البريد الإلكتروني وكلمة المرور الخاصة بك.

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);
}

إذا كنت تريد إرسال بريد إلكتروني في الخلفية، فيرجى القيام بما يلي

 public void SendEmail(string address, string subject, string message)
 {
 Thread threadSendMails;
 threadSendMails = new Thread(delegate()
    {

      //Place your Code here 

     });
  threadSendMails.IsBackground = true;
  threadSendMails.Start();
}

وإضافة مساحة الاسم

using System.Threading;

استخدم هذه الطريقة

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);

لا تنسى هذا :

using System.Net;
using System.Net.Mail;

نصيحة واحدة!تحقق من البريد الوارد للمرسل، ربما تحتاج إلى السماح بتطبيقات أقل أمانًا.يرى: https://www.google.com/settings/security/lesssecureapps

جرب هذا،

    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());
        }
    }

تغيير المرسل على البريد الإلكتروني Gmail / Outlook.com:

لمنع الانتحال - لن يسمح لك Gmail/Outlook.com بالإرسال من اسم حساب مستخدم عشوائي.

إذا كان لديك عدد محدود من المرسلين، فيمكنك اتباع هذه التعليمات ثم تعيين From الحقل إلى هذا العنوان: إرسال البريد من عنوان مختلف

إذا كنت تريد الإرسال من عنوان بريد إلكتروني عشوائي (مثل نموذج التعليقات على موقع الويب حيث يقوم المستخدم بإدخال بريده الإلكتروني ولا تريد أن يرسل إليك بريدًا إلكترونيًا مباشرةً) فإن أفضل ما يمكنك فعله هو ما يلي:

        msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));

سيسمح لك هذا فقط بالضغط على "رد" في حساب بريدك الإلكتروني للرد على معجبي فرقتك الموسيقية في صفحة التعليقات، لكنهم لن يحصلوا على بريدك الإلكتروني الفعلي مما قد يؤدي على الأرجح إلى عدد كبير من الرسائل غير المرغوب فيها.

إذا كنت في بيئة خاضعة للرقابة، فهذا يعمل بشكل رائع، ولكن يرجى ملاحظة أنني رأيت بعض عملاء البريد الإلكتروني يرسلون إلى عنوان "من" حتى عند تحديد الرد (لا أعرف أي منها).

واجهت نفس المشكلة، ولكن تم حلها بالانتقال إلى إعدادات أمان Gmail و السماح بالتطبيقات الأقل أمانًا.يعمل الرمز من Domenic & Donny، ولكن فقط إذا قمت بتمكين هذا الإعداد

إذا قمت بتسجيل الدخول (إلى Google)، يمكنك المتابعة هذا الارتباط والتبديل "شغله" ل "الوصول للتطبيقات الأقل أمانًا"

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();
     }
}
}
}

فيما يلي إحدى الطرق لإرسال البريد والحصول على بيانات الاعتماد من 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;
    }

}

والقسم المقابل في 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>

المشكلة بالنسبة لي كانت أن بلدي تحتوي كلمة المرور على شرطة مائلة سوداء "\" فيه، والذي قمت بنسخه ولصقه دون أن أدرك أنه سيسبب مشاكل.

جرب هذه

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)
        { }
        catch (SmtpException ex)
        { }
        finally
        {
            mailSender = null;
            mailMessage.Dispose();
        }
        return false;
}

النسخ من إجابة أخرى, ، تعمل الطرق المذكورة أعلاه ولكن Gmail يستبدل دائمًا البريد الإلكتروني "من" و"الرد على" بحساب Gmail الفعلي للإرسال.يبدو أن هناك عملاً حول ولكن:

http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html

"3.في علامة التبويب "الحسابات"، انقر على الرابط "أضف عنوان بريد إلكتروني آخر تملكه" ثم قم بتأكيده"

أو ربما هذا

التحديث 3:يقول القارئ ديريك بينيت، "الحل هو الدخول إلى إعدادات Gmail الخاصة بك: الحسابات و"جعلها افتراضية" حسابًا آخر غير حساب Gmail الخاص بك.سيؤدي هذا إلى قيام Gmail بإعادة كتابة الحقل "من" باستخدام عنوان البريد الإلكتروني للحساب الافتراضي مهما كان."

يمكنك تجربة Mailkit.إنها تمنحك وظيفة أفضل ومتقدمة لإرسال البريد.يمكنك العثور على المزيد من هذا هنا مثال

    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);
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top