Unity中自动发送邮件功能

记个笔记

因项目需求需要做一个发送带有附件的邮件功能,话不多说先上核心代码,最后会说遇到的坑

private void Send()
    {
      //判断输入的字符串是否是邮箱
        if (IsEmail(EmailText.text)&& !IsSending)
        {
            IsSending = true;
            MailMessage mail = new MailMessage();
          //设置发件人邮箱
            mail.From = new MailAddress("[email protected]");
                //设置收件人邮箱地址
            mail.To.Add(EmailText.text);
            if (cCEmailManager != null)
            {
                foreach (var email in cCEmailManager.CCEmailList)
                {
                  //设置抄送人邮箱地址
                    mail.CC.Add(email.CCEmailAccount);
                }
            }
          //设置邮件内容
            string content = string.Empty;
            if (TitleText != null && TitleText.text != string.Empty)
            {
                content = TitleText.text;
            }
            else
            {
                content = ExportDatas.Instance.GetFileName();
            }
          //设置主体的字符编码
            mail.BodyEncoding = System.Text.Encoding.UTF8;
          //设置邮件标题
            mail.Subject = content;
          //设置邮件内容
            mail.Body = content;
          //下面是创建设置发件人邮箱的类型端口密码等
            SmtpClient smtpServer = new SmtpClient(/*"smtp.qq.com"*/"smtp.exmail.qq.com");
            //smtpServer.Port = 465/*587*/;
            smtpServer.Credentials = new System.Net.NetworkCredential("[email protected]", "xxxxxx") as ICredentialsByHost;
            smtpServer.EnableSsl = true;
            ServicePointManager.ServerCertificateValidationCallback =
                delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                { return true; };
          //下面是添加邮件附件
            mail.Attachments.Add(new Attachment(ExportDatas.Instance.GetFilePath()));
          //下面添加发送完成的回调,方法自己写
            smtpServer.SendCompleted += new SendCompletedEventHandler(SendEmailCompleted);
            if (SendTips != null) SendTips.gameObject.SetActive(true);
            if (SendingTips != null) SendingTips.gameObject.SetActive(true);
            if (SendCompletedTips != null) SendCompletedTips.gameObject.SetActive(false);
            Debug.Log("发送中");
            smtpServer.SendMailAsync(mail);
        }
        else
        {
            //IsSending = false;
            UIToastTool.Instance.Show("请填写正确的邮箱地址");
        }
    }


基本上发送邮件的核心代码就上面这块,下面说下遇到的坑

1、设置发件人邮箱类型端口等的时候,如果是个人的QQ邮箱,那么设置端口没问题,如果是腾讯企业邮箱请把端口设置去掉,虽然官方文档上有写需要设置端口,但是一旦设置就会发送失败。

2、发件人密码并不是真实的注册邮箱时填写的登入密码,而是设置能自动发送邮件权限时生产的编码,至于怎么设置权限,根据不同的邮箱类型请去具体的官方文档中查看

3、发送邮件成功的回调会与一些代码冲突,例如他会和 windows提供的下面这个选择文件机夹位置的方法冲突 ,导致会接收不到回调信息

//System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog(); 

猜你喜欢

转载自blog.csdn.net/m0_69824302/article/details/130773288