Unity学习篇之一键添加附件并发送邮件(支持多平台)

最近接触到通过Unity发送邮件的功能,需要将正文以及本地的文件作为附件发送到指定邮箱,最后通过

SMTP实现了该功能,试了下QQ邮箱、163邮箱,亲测可用,总结如下:


QQ邮箱

QQ邮箱需要打开SMTP服务点此查看教程

using UnityEngine;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public class MyExcel : MonoBehaviour
{

    //默认文件目录
    private string UnityPath = @"C:/Users/Administrator/Desktop/1.xlsx";

    void OnGUI()
    {
        if (GUI.Button(new Rect(0, 0, 100, 40), "Send"))
        {
            SendEmail(UnityPath);
        }
    }

    /// <summary>
    /// 邮件发送
    /// </summary>
    private void SendEmail(string UnityPath)
    {
        MailMessage mail = new MailMessage();
        //发送邮箱的地址
        mail.From = new MailAddress("[email protected]");
        //收件人邮箱地址 如需发送多个人添加多个Add即可
        mail.To.Add("[email protected]");
        //标题
        mail.Subject = "Test Mail";
        //正文
        mail.Body = "这是一个测试邮件";
        //添加一个本地附件 
        mail.Attachments.Add(new Attachment(UnityPath));

        //所使用邮箱的SMTP服务器
        SmtpClient smtpServer = new SmtpClient("smtp.qq.com");
        //SMTP端口
        smtpServer.Port = 587;
        //账号密码 一般邮箱会提供一串字符来代替密码
        smtpServer.Credentials = new System.Net.NetworkCredential("[email protected]", "Password") as ICredentialsByHost;
        smtpServer.EnableSsl = true;
        ServicePointManager.ServerCertificateValidationCallback =
            delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            { return true; };

        smtpServer.Send(mail);
        Debug.Log("success");
    }
}

 163邮箱

 若使用163邮箱发送只需修改SMTP端口以及服务器即可,别忘了账号密码

        //所使用邮箱的SMTP服务器
        SmtpClient smtpServer = new SmtpClient("smtp.163.com");
        //SMTP端口
        smtpServer.Port = 25;
 大部分邮箱都可以使用该方法,试了一下阿里云企业邮箱发现Unity不能够识别阿里云的SMTP服务器。。。





猜你喜欢

转载自blog.csdn.net/York_New/article/details/79115249