Program Tip

Gmail을 통해 .NET에서 이메일 보내기

programtip 2020. 9. 28. 09:56
반응형

Gmail을 통해 .NET에서 이메일 보내기


이메일을 보내는 데 호스트에 의존하는 대신 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);
}

다른 답변이 "서버에서"작동하려면 먼저 Gmail 계정에서 보안 수준이 낮은 앱대한 액세스를 사용 설정 하세요.

최근 Google이 보안 정책을 변경 한 것 같습니다. https://support.google.com/accounts/answer/6010255?hl=en-GB에 설명 된대로 계정 설정을 변경할 때까지 최고 평점 답변이 더 이상 작동하지 않습니다.여기에 이미지 설명 입력

여기에 이미지 설명 입력

2016 년 3 월부터 구글이 설정 위치를 다시 변경했습니다!


첨부 파일로 이메일을 보내는 것입니다 .. 간단하고 짧습니다 ..

출처 : 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은 최신 보안 표준을 사용하지 않는 일부 앱이나 기기의 로그인 시도를 차단할 수 있습니다. 이러한 앱과 기기는 침입하기가 더 쉽기 때문에 차단하면 계정을 더 안전하게 유지할 수 있습니다.

최신 보안 표준을 지원하지 않는 앱의 예는 다음과 같습니다.

  • iOS 6 이하가 설치된 iPhone 또는 iPad의 Mail 앱
  • 8.1 릴리스 이전의 Windows Phone의 메일 앱
  • Microsoft Outlook 및 Mozilla Thunderbird와 같은 일부 데스크톱 메일 클라이언트

따라서 Google 계정에서 보안 수준이 낮은 로그인 을 활성화 해야합니다.

Google 계정에 로그인 한 후 다음으로 이동하십시오.

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

내 버전은 " Send Email In C # Using 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 #을 사용하여 메일을 보내기위한 샘플 작업 코드입니다. 아래 예제에서는 Google의 smtp 서버를 사용하고 있습니다.

코드는 매우 자명하며 이메일과 비밀번호를 이메일과 비밀번호 값으로 바꿉니다.

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>

나에게 문제는 내 암호에 검은 색 슬래시 "\"가 있어서 문제가 발생할 것이라는 사실을 깨닫지 못한 채 복사하여 붙여 넣었다는 것입니다.


다른 답변 에서 복사 하면 위의 방법이 작동하지만 Gmail은 항상 '보낸 사람'및 '답장'이메일을 실제 보내는 Gmail 계정으로 바꿉니다. 그러나 분명히 해결 방법이 있습니다.

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

"3. 계정 탭에서"내가 소유 한 다른 이메일 주소 추가 "링크를 클릭 한 다음 확인하십시오."

아니면 이것은

업데이트 3 : Reader Derek Bennett는 "해결 방법은 Gmail 설정 : 계정으로 이동하여 Gmail 계정 이외의 계정을"기본값으로 설정 "하는 것입니다. 이렇게하면 Gmail에서 기본 계정의 이메일이 무엇이든 보낸 사람 필드를 다시 작성합니다. 주소입니다. "


이걸로 해봐

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)
        { 
          // Write the exception to a Log file.
        }
        catch (SmtpException ex)
        { 
           // Write the exception to a Log file.
        }
        finally
        {
            mailSender = null;
            mailMessage.Dispose();
        }
        return false;
}

Gmail의 보안 문제를 방지하려면 먼저 Gmail 설정에서 앱 비밀번호를 생성해야하며, 2 단계 인증을 사용하는 경우에도 실제 비밀번호 대신이 비밀번호를 사용하여 이메일을 보낼 수 있습니다.


시도해 볼 수 있습니다 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);
    }

참고 URL : https://stackoverflow.com/questions/32260/sending-email-in-net-through-gmail

반응형