문제

내 호스트에게 이메일을 보내는 대신 Gmail 계정을 사용하여 이메일 메시지를 보낼 생각이었습니다.이메일은 내가 쇼에서 연주하는 밴드에게 보내는 개인화 된 이메일입니다.할 수 있습니까?

도움이 되었습니까?

해결책

지원 중단 된 System.Net.Mail가 아닌 System.Web.Mail를 사용해야합니다.System.Web.Mail로 SSL을 수행하는 것은 해키 확장의 엉망입니다. 라코 디스

다른 팁

위 답변이 작동하지 않습니다.DeliveryMethod = SmtpDeliveryMethod.Network를 설정해야합니다. 그렇지 않으면 " 클라이언트가 인증되지 않았습니다 "오류가 표시됩니다.또한 항상 시간 제한을 두는 것이 좋습니다.

수정 된 코드 : 라코 디스

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

최근 Google에서 보안 정책을 변경 한 것 같습니다. https://support.google.com/accounts/answer/6010255?hl=en-GB 여기에 이미지 설명 입력

여기에 이미지 설명 입력

2016 년 3 월부터 Google에서 설정 위치를 다시 변경했습니다!

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

출처 : http : //coding-issues.blogspot.in / 2012 / 11 / sending-email-with-attachments-from-c.html 라코 디스

Google은 최신 보안 표준을 사용하지 않는 일부 앱이나 기기의 로그인 시도를 차단할 수 있습니다. 이러한 앱과 기기는 침입하기가 더 쉽기 때문에 차단하면 계정을 더 안전하게 유지하는 데 도움이됩니다.

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

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

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

    Google 계정에 로그인 한 후 다음으로 이동 :

    https://myaccount.google.com/lesssecureapps
    또는
    https://www.google.com/settings/security/lesssecureapps

    C #에서는 다음 코드를 사용할 수 있습니다. 라코 디스

다음은 내 버전입니다. " Gmail을 사용하여 C #으로 이메일 보내기 ". p> 라코 디스

이 기능을 사용하려면 다른 앱에서 액세스 할 수 있도록 Gmail 계정을 활성화해야했습니다.이 작업은 '보안 수준이 낮은 앱 사용'과 또한 다음 링크를 사용하여 수행됩니다. https://accounts.google.com/b/0/DisplayUnlockCaptcha

이 코드가 제대로 작동하기를 바랍니다.시도해 볼 수 있습니다. 라코 디스

포함 라코 디스

그리고 라코 디스

출처 : ASP.NET C #으로 이메일 보내기

아래는 C #을 사용하여 메일을 보내기위한 샘플 작업 코드입니다. 아래 예에서는 Google의 smtp 서버를 사용하고 있습니다.

코드는 자명하며 이메일과 비밀번호를 이메일과 비밀번호 값으로 대체합니다. 라코 디스

백그라운드 이메일을 보내려면 다음을 수행하십시오. 라코 디스

네임 스페이스 추가 라코 디스

이 방법으로 사용 라코 디스

이것을 잊지 마세요 : 라코 디스

One Tip! Check the sender inbox, maybe you need allow less secure apps. See: https://www.google.com/settings/security/lesssecureapps

Try This,

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

Changing sender on Gmail / Outlook.com email:

To prevent spoofing - Gmail/Outlook.com won't let you send from an arbitrary user account name.

If you have a limited number of senders you can follow these instructions and then set the From field to this address: Sending mail from a different address

If you are wanting to send from an arbitrary email address (such as a feedback form on website where the user enters their email and you don't want them emailing you directly) about the best you can do is this :

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

This would let you just hit 'reply' in your email account to reply to the fan of your band on a feedback page, but they wouldn't get your actual email which would likely lead to a tonne of spam.

If you're in a controlled environment this works great, but please note that I've seen some email clients send to the from address even when reply-to is specified (I don't know which).

I had the same issue, but it was resolved by going to gmail's security settings and Allowing Less Secure apps. The Code from Domenic & Donny works, but only if you enabled that setting

If you are signed in (to Google) you can follow this link and toggle "Turn on" for "Access for less secure apps"

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

Here is one method to send mail and getting credentials from 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;
    }

}

And the corresponding section in 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>

The problem for me was that my password had a blackslash "\" in it, which I copy pasted without realizing it would cause problems.

Try this one

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

Copying from another answer, the above methods work but gmail always replaces the "from" and "reply to" email with the actual sending gmail account. apparently there is a work around however:

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

"3. In the Accounts Tab, Click on the link "Add another email address you own" then verify it"

Or possibly this

Update 3: Reader Derek Bennett says, "The solution is to go into your gmail Settings:Accounts and "Make default" an account other than your gmail account. This will cause gmail to re-write the From field with whatever the default account's email address is."

You can try Mailkit. Its give you better and advance functionlity for send mail. You can find more from this Here is an example

    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