星期四, 4月 17, 2014

在Unity 用Gmail帳號寄信 C#

using UnityEngine;//純Log用
using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public class Mail {
public void SendMail() {
     MailMessage mail = new MailMessage();
     mail.From = new MailAddress("寄件者信箱");
     mail.To.Add("收件者信箱");
     mail.Subject = "主旨";

     try{
          //內文附圖
          AlternateView plainView = AlternateView.CreateAlternateViewFromString("<p>",null, "text/plain");
          mail.AlternateViews.Add(plainView);
          AlternateView htmlView = CreateAlternateView("Floor0001");
          mail.AlternateViews.Add(htmlView);

          
          //附件
          FileStream imageFileStream = new FileStream(Application.streamingAssetsPath+"/Floor0001.jpg",FileMode.Open);
          Attachment attachment = new Attachment(imageFileStream,"Floor0001.jpg");
          mail.Attachments.Add(attachment);
          
          Debug.Log("Success");
     }catch{
          Debug.Log("Fail");
     }

     SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
     smtpServer.Port = 587;
     smtpServer.Credentials = new System.Net.NetworkCredential("寄件者信箱", "寄件者密碼") as ICredentialsByHost;
     smtpServer.EnableSsl = true;
     ServicePointManager.ServerCertificateValidationCallback = 
          delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {  return true; };
     smtpServer.Send(mail);
     }

     private AlternateView CreateAlternateView(string pictureName) {
          string htmlBody = "<html><body><img src=cid:"+pictureName+"A></img><p>" +
                    "<img src=cid:"+pictureName+"B></img><p>" +
                    "Send by unity3d!</body></html>";
          AlternateView alternateView = AlternateView.CreateAlternateViewFromString(
                    htmlBody,
                    null, "text/html");

          LinkedResource imageA = new LinkedResource(Application.streamingAssetsPath+"/"+pictureName+"A.jpg" );
          imageA.ContentId = pictureName+"A";
          LinkedResource imageB = new LinkedResource(Application.streamingAssetsPath+"/"+pictureName+"B.jpg" );
          imageB.ContentId = pictureName+"B";
          alternateView.LinkedResources.Add(imageA);
          alternateView.LinkedResources.Add(imageB);
          return alternateView;
     }

}

4 則留言:

  1. 感謝您的分享<(_ _)>
    有一事請教...請問您輸出EXE檔後可以使用嗎?
    Unity執行沒問題但輸出後就失靈了XD

    回覆刪除
    回覆
    1. Hi, 豪子您好
      我還真沒想到有人來我這勒XD
      那時沒有輸出成EXE因為是要用在Windows store app的
      然後因為Windows store app 的API跟C#不完全相容
      所以這段程式整個無法使用
      也就沒有研究EXE的部分了
      抱歉喔><

      刪除
    2. 沒關係,我已經找到解決問題的方法哩
      在PlayerSetting裡把Api Compatibility Level的.Net 2.0 subset
      改成.Net 2.0 就可以用了~
      提供給後面來的人看看囉

      刪除