Created
December 19, 2017 02:50
-
-
Save hiroakioishi/9fe81b33367f422fd4c77158ce424335 to your computer and use it in GitHub Desktop.
非同期でUnityからメール(GMail)を送信する. 場合によってはGMailのセキュリティ設定で、 安全性の低いアプリのアクセスを オン にしなければならない. https://www.google.com/settings/security/lesssecureapps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class AsyncMailSender : MonoBehaviour { | |
public string MailFromAddress = "from@gmail.com"; | |
public string MailHost = "smtp.gmail.com"; | |
public int MailPort = 587; | |
public string MailPassword = "frompassword"; | |
public string MailToAddress = "to@gmail.com"; | |
public string MailSubject = "Subject"; | |
public string MailBody = "Body"; | |
private System.Net.Mail.SmtpClient _stampClient = null; | |
void Update () { | |
if (Input.GetKeyUp ("s")) { | |
_send (); | |
} | |
if (Input.GetKeyUp ("c")) { | |
_cancelSend (); | |
} | |
} | |
void _send () { | |
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage ( | |
MailFromAddress, | |
MailToAddress, | |
MailSubject, | |
MailBody | |
); | |
if (_stampClient == null) { | |
_stampClient = new System.Net.Mail.SmtpClient (MailHost); | |
_stampClient.SendCompleted += new System.Net.Mail.SendCompletedEventHandler (_sendCompleteHandler); | |
} | |
_stampClient.Port = MailPort; | |
_stampClient.EnableSsl = true; | |
_stampClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; | |
_stampClient.UseDefaultCredentials = false; | |
_stampClient.Credentials = new System.Net.NetworkCredential (MailFromAddress, MailPassword) as System.Net.ICredentialsByHost; | |
System.Net.ServicePointManager.ServerCertificateValidationCallback = | |
delegate | |
( | |
object s, | |
System.Security.Cryptography.X509Certificates.X509Certificate certificate, | |
System.Security.Cryptography.X509Certificates.X509Chain chain, | |
System.Net.Security.SslPolicyErrors sslPolicyErrors | |
) | |
{ | |
return true; | |
}; | |
_stampClient.SendAsync (msg, msg); | |
} | |
void _cancelSend () { | |
if (_stampClient != null) { | |
_stampClient.SendAsyncCancel (); | |
} | |
} | |
void _sendCompleteHandler (object sender, System.ComponentModel.AsyncCompletedEventArgs e) { | |
System.Net.Mail.MailMessage msg = (System.Net.Mail.MailMessage) e.UserState; | |
if (e.Cancelled) { | |
Debug.Log ("<color=yellow>Cancelled sending message.</color>"); | |
} else if (e.Error != null) { | |
Debug.Log ("<color=red>An error has occurred.</color>"); | |
Debug.Log (e.Error.ToString ()); | |
} else { | |
Debug.Log ("<color=lime>Mail has been sent.</color>"); | |
} | |
msg.Dispose (); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment