gpt4 book ai didi

c# - 在unity3D中使用C#发送邮件?

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:36 29 4
gpt4 key购买 nike

我需要在 Unity3D 中使用 C# 发送电子邮件。我已经这样做了,但是遇到了运行时警告。请帮我解决以下警告。

警告:名为“Program”的脚本文件中定义的类不是从 MonoBehaviour 或 ScriptableObject 派生的

我的代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;

namespace EMail
{
class Program
{
static void Main(string[] args)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtpC = new SmtpClient("smtp.gmail.com");
//From address to send email
mail.From = new MailAddress("From@gmail.com");
//To address to send email
mail.To.Add("To@gmail.com");
mail.Body = "This is a test mail from C# program";
mail.Subject = "TEST";
smtpC.Port = 587;
//Credentials for From address
smtpC.Credentials =(System.Net.ICredentialsByHost) new System.Net.NetworkCredential("EmailID", "password");
smtpC.EnableSsl = true;
smtpC.Send(mail);
Console.WriteLine("Message sent successfully");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.GetBaseException());
Console.ReadLine();
}
}
}
}

最佳答案

您需要实际阅读您的错误消息,它会告诉您答案:

warning:The class defined in the script file named 'Program' is not derived from MonoBehaviour or ScriptableObject

要在 Unity 中制作自定义对象,您必须使它们从 ScriptableObject 或 MonoBehaviour 对象扩展,以便在您的游戏引擎中使用它们。 ScriptableObject 适用于不需要附加到游戏内对象的代码,而 MonoBehaviour 则需要。

在这种情况下,作为电子邮件处理程序,您需要使用可编写脚本的对象,因为它不会附加到场景对象。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using UnityEngine;
//^Make sure to include UnityEngine if you will connect to other game objects

//Extend ScriptableObject to use custom code
public class EmailHandler extends ScriptableObject
{
public void SendEmail()
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtpC = new SmtpClient("smtp.gmail.com");
//From address to send email
mail.From = new MailAddress("From@gmail.com");
//To address to send email
mail.To.Add("To@gmail.com");
mail.Body = "This is a test mail from C# program";
mail.Subject = "TEST";
smtpC.Port = 587;
//Credentials for From address
smtpC.Credentials =(System.Net.ICredentialsByHost) new System.Net.NetworkCredential("EmailID", "password");
smtpC.EnableSsl = true;
smtpC.Send(mail);

//Change Console.Writeline to Debug.Log
Debug.Log ("Message sent successfully");
}
catch (Exception e)
{
Debug.Log(e.GetBaseException());
//You don't need or use Console.ReadLine();
}
}
}

使用它应该可以解决您的问题并帮助您完成类(class)。

关于c# - 在unity3D中使用C#发送邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18202573/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com