Call Android Email intent from Unity script - c#

I have a feedback button in unity game, if the user clicks on it then it should launch an default email app with subject, email address filled already. I have done this in Android app but how to call it from unity?
Are there any other better approaches for feedback other than this?

What you are doing is plugin. You don't need plugin for this.
You can simply send email with:
void sendEmail(string toEmail, string emailSubject, string emailBody)
{
emailSubject = System.Uri.EscapeUriString(emailSubject);
emailBody = System.Uri.EscapeUriString(emailSubject);
Application.OpenURL("mailto:" + toEmail + "?subject=" + emailSubject + "&body=" + emailBody);
}
To send, call:
sendEmail("example#example.com", "Test", "This is a text\r\nAnother test\r\nAnd another text");
This will work on PC, Android and iOS. I don't know for Mac.
Now if you still want to use Android API's, you still don't need to make a plugin for this. You can use AndroidJavaObject and write your email code with Android API.
private static void SendMail(string subject, string body, bool useHTML)
{
using (var intentClass = new AndroidJavaClass("android.content.Intent"))
{
// intent = new Intent(Intent.ACTION_SEND);
using (var intentObject = new AndroidJavaObject("android.content.Intent", intentClass.GetStatic<string>("ACTION_SEND")))
{
// Setting text type
if (useHTML)
// intent.setType("text/html");
intentObject.Call<AndroidJavaObject>("setType", "text/html");
else
// intent.setType("message/rfc822");
intentObject.Call<AndroidJavaObject>("setType", "message/rfc822");
// intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_SUBJECT"), subject);
// Setting emailBody
if (useHTML)
{
// intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(emailBody));
using (var html = new AndroidJavaClass("android.text.Html"))
{
var htmlBody = html.CallStatic<AndroidJavaObject>("fromHtml", body);
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"), htmlBody);
}
}
else
{
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"), body);
}
using (var unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
using (var currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity"))
{
currentActivity.Call("startActivity", intentObject);
}
}
}
}
}
And to call it SendMail("test", "Message", false);. You can improve it and add more features to it. This last example was lifted from here.

#Programmer's (native-method) answer is correct; but when the user is prompted to select an app to send the email, there's a good chance the user will have the possibility to select apps other than e-mail apps; e.g. WhatsApp. We don't want this to happen. As stated in the docs the way we could ensure that only e-mail apps will be shown to the user, is to use Intent.ACTION_SENDTO and intent.setData(Uri.parse("mailto:").
private void SendMail(string subject, string body)
{
using (var intentClass = new AndroidJavaClass("android.content.Intent"))
{
// intent = new Intent(Intent.ACTION_SEND);
using (var intentObject = new AndroidJavaObject("android.content.Intent", intentClass.GetStatic<string>("ACTION_SENDTO")))
{
//intent.setData(Uri.parse("mailto:"));
var uriClass = new AndroidJavaClass("android.net.Uri");
var uriObject = uriClass.CallStatic<AndroidJavaObject>("parse", "mailto:");
intentObject.Call<AndroidJavaObject>("setData", uriObject);
// intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_SUBJECT"), subject);
//intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_EMAIL"), "youremail#abc.xyz");
string[] email = { "youremail#abc.xyz" };
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_EMAIL"), email);
// Setting emailBody
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"), body);
using (var unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
using (var currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity"))
{
currentActivity.Call("startActivity", intentObject);
}
}
}
}
}
Replace youremail#abc.xyz with the e-mail you intend to send the e-mail to.
The question is, why do all this hassle instead of simply sending the e-mail like stated below:
void sendEmail(string toEmail, string emailSubject, string emailBody)
{
emailSubject = System.Uri.EscapeUriString(emailSubject);
emailBody = System.Uri.EscapeUriString(emailSubject);
Application.OpenURL("mailto:" + toEmail + "?subject=" + emailSubject +
"&body=" + emailBody);
}
You might want to add HTML or some non-Latin text (e.g. Japanese, Arabic) to your e-mail's body. using System.Uri.EscapeUriString is going to mess that up. In that case, the native method will be your method of choice.

On Button click you have to call:
public void OpenActivity()
{
var androidJC = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
var jo = androidJC.GetStatic<AndroidJavaObject>("currentActivity");
// Accessing the class to call a static method on it
var jc = new AndroidJavaClass("com.xyz.abc.StartActivity");
// Calling a Call method to which the current activity is passed
jc.CallStatic("Call", jo);
}
}
Replace it by your activity and package name
var jc = new AndroidJavaClass("com.xyz.abc.StartActivity");

Related

ASP.net MVC 5 project SMTP function error [duplicate]

This question already has answers here:
Sending email through Gmail SMTP server with C#
(31 answers)
Closed 3 years ago.
As the title above, I have created a project with simple log-in and registration. Inside the program, I have use System.Net.Mail.SmtpException to send the email verification to the user email. I have done created the email but when I click on create a new account, I met this problem as well.
System.Net.Mail.SmtpException: 'The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
From the information I search, I found out someone say I need to make my email 2-step verification. I did it but the problem still there.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using Food_Founder.Models;
namespace Food_Founder.Controllers
{
public class UserController : Controller
{
//Registration
[HttpGet]
public ActionResult Registration()
{
return View();
}
//Post Registration
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")]User user)
{
//Model Validation
bool Status = false;
string message = "";
//Email is already exist
if (ModelState.IsValid)
{
#region Email is already exist
var isExist = IsEmailExist(user.Email);
if (isExist)
{
ModelState.AddModelError("EmailExist", "Email already exist");
return View(user);
}
#endregion
#region Generate Activation Code
user.ActivationCode = Guid.NewGuid();
#endregion
#region Password Hashing
user.Password = Crypto.Hash(user.Password);
user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword);
#endregion
user.IsEmailVerified = false;
#region Save Data to Database
using (myDatabaseEntities myDatabase = new myDatabaseEntities())
{
myDatabase.Users.Add(user);
myDatabase.SaveChanges();
//Send Email to User
SendVerificationLinkEmail(user.Email, user.ActivationCode.ToString());
message = "Registration successfully done. Account activation link" +
"has been send to your Email:" + user.Email + "Please go check and activate your account";
Status = true;
}
#endregion
}
else
{
message = "Invalid Request";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(user);
}
//Verify Email
//Verify Email Link
//Login
//Login POST
//Logout
[NonAction]
public Boolean IsEmailExist(string email)
{
using (myDatabaseEntities myDatabase = new myDatabaseEntities())
{
var v = myDatabase.Users.Where(a => a.Email == email).FirstOrDefault();
return v != null;
}
}
[NonAction]
public void SendVerificationLinkEmail(string email, string activationCode)
{
var verifyUrl = "/User/VerifyAccount/" + activationCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);
var fromEmail = new MailAddress("yukwokyao2#gmail.com", "yukwokyao");
var toEmail = new MailAddress(email);
var fromEmailPassword = "********";
string subject = "Your account is successfully created!";
string body = "<br/><br/>We are excited to tell you that your FoodFounder account is" +
"successfully created. Please click the below link to verify your FoodFounder account" +
"<a href = '" + link + "' >" + link + "</a>";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
};
using (var message = new MailMessage(fromEmail, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
smtp.Send(message);
}
}
}
The code above is the controller class I created. The problem I found is there so that I didn't put any other design html code in here. The most weird part is even I met this problem, the data I register still can key-in into the database but this annoying problem still exist there. Anywhere, if anything I miss put, please inform me ya.. Thank you.
If you are using your Gmail account as SMTP server you need to allow access from what Google calls "less secure apps". You can enable it from your Google settings.

Sending Message Using Twilio-C#

Hy... I'm learning twilio rightnow, and I have seen a post here http://www.markhagan.me/Samples/Send-SMS-Using-Twilio-ASPNet
I have made my own code because in above site "sendSMSMessage" is deprecated now, but Here is my code :
using System.Text;
using System.Threading.Tasks;
using Twilio;
namespace SMSUsingTwilio
{
class Program
{
static void Main(string[] args)
{
String ACCOUNT_SID = "ACMYSID";
String AUTH_TOKEN = "40MYAUTHTOKEN";
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Message Response = client.SendMessage("(732)305-8856", "+6285220446195", "Hellow Hyosoka Poipo :D");
Console.WriteLine(Response.Status);
Console.WriteLine(Response.AccountSid);
Console.WriteLine("SMS Berhasil di kirim");
Console.ReadLine();
}
}
}
The problem is I don't any sms message to my phone number and even I don't get any response in my C# project:
So what's wrong here...?? Please help..Thank you so much...:)
After seeing mr.David answer, I realized that my phone number was not yet verified. So go to this link for verifying my number:
https://www.twilio.com/user/account/phone-numbers/verified
After that, I run my project agian and here is the result :
Yeeeiii...Thanks so much for your comments and answer... I really appreciate it... :)
The above looks fine:
var message = client.SendMessage("(732)305-8856", "+6285220446195", "Hellow Hyosoka Poipo :D");
Example:
static void Main(string[] args)
{
string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string AuthToken = "[AuthToken]";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var message = twilio.SendMessage("(732)305-8856", "+6285220446195", "Hellow Hyosoka Poipo :D");
);
Console.WriteLine(message.Sid);
}
Check this out:
https://www.twilio.com/docs/api/rest/sending-messages
I don't recognise your phone numbers, if the above example does not work it will be an issue with your account or the number format.
First of all, you need to install a Twillio NuGet package from Numget Manager
Otherwise,
You can write code Install-Package Twilio
in Package manager console.
You need to create Twillo account from https://www.twilio.com
Now you get AccountId, AuthToken etc
Then you will need to implement the following code in your project:
public async Task<string> SendTwilioSMS(string phoneNumber, string SMS)
{
string returnMessage = string.Empty;
string bodySMS = SMS;
var twilioAccountSid = "AC754fec249d22766caf0ae4e58a158271";
var twilioAuthToken = "cfecd5ff4d751677fc2e2875e3739b55";
var twilioMessagingServiceSid = "MGd57fcc863cb37dcff135aca43b4bb7d1";
var twilioPhoneNumber = "+919714285344";
bodySMS = SMS;
TwilioClient.Init(twilioAccountSid, twilioAuthToken);
try
{
MessageResource twillioResult = await MessageResource.CreateAsync(
to: new PhoneNumber(phoneNumber),
from: new PhoneNumber(twilioPhoneNumber),
body: bodySMS,
messagingServiceSid: twilioMessagingServiceSid
);
returnMessage = "Message sent";
}
catch (Exception err)
{
returnMessage = err.Message;
}
return returnMessage;
}
The value should be brought from appsettings file if using .Net Core.
public async Task SendSMS()
{
var sid = "0845-373A-90fy-5790";
var authToken = "5a983-498f94-2849o8934-28455s9";
try
{
TwilioClient.Init(sid , authToken );
var message = await MessageResource.CreateAsync(
body: "Hi",
from: new Twilio.Types.PhoneNumber("+12564598"),
to: new Twilio.Types.PhoneNumber("9467345243"));
}
catch (Exception ex)
{
//Log Exception
}
}

C# - Send email with inline attachment WITHOUT Outlook's paperclip icon?

I have a system that sends emails with inline pictures. The problem is how Outlook 2013 displays the attachments. Can I update my code in a way that tells outlook not to display the paperclip icon seen here?
The idea is that I only want to display this icon when full sized pictures are attached. Not inline attachments.
Here's the code that generates the email. Create a basic console app, specify your To / mailserver / picture path, and run.
static void Main(string[] args)
{
Console.WriteLine("Prepping email message....");
var subject = "Test Subject With Inline";
var message = "<p>This is a test message.</p><br/><br/><p>[CompanyLogo]</p>";
var to = new List<string>();
to.Add("My.Name#company.com");
Console.WriteLine("Sending email message....");
if (SendMessageToFrom(subject, message, to, new List<string>()))
{
Console.WriteLine("Email sent! Check your inbox.");
}
else
{
Console.WriteLine("Error sending email!");
}
}
public static bool SendMessageToFrom(String subject, String message, List<String> to, List<String> cc)
{
try
{
// Construct the email
var sendMessage = new MailMessage()
{
IsBodyHtml = true,
From = new MailAddress("noreply#company.com"),
Subject = subject,
Body = message
};
if (sendMessage.Body.Contains("[CompanyLogo]"))
{
sendMessage.AlternateViews.Add(EmbedLogo(sendMessage.Body));
}
// Add the list of recipients
foreach (var recipient in to)
{
sendMessage.To.Add(recipient);
}
foreach (var recipient in cc)
{
sendMessage.CC.Add(recipient);
}
//Specify the SMTP server
var smtpServerName = "mailserver.company.com";
var mailClient = new SmtpClient(smtpServerName);
mailClient.Send(sendMessage);
return true;
}
catch
{
throw;
}
}
private static AlternateView EmbedLogo(string html)
{
var inline = new LinkedResource("img\\company-logo.jpg");
inline.ContentId = Guid.NewGuid().ToString();
html = html.Replace("[CompanyLogo]", string.Format(#"<img src='cid:{0}'/>", inline.ContentId));
var result = AlternateView.CreateAlternateViewFromString(html, null, System.Net.Mime.MediaTypeNames.Text.Html);
result.LinkedResources.Add(inline);
return result;
}
Update: Here's the code that did the trick:
private static MailMessage EmbedLogo(MailMessage mail)
{
var inline = new Attachment("img\\company-logo.jpg");
inline.ContentId = Guid.NewGuid().ToString();
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
mail.Body = mail.Body.Replace("[CompanyLogo]", string.Format(#"<img src='cid:{0}'/>", inline.ContentId));
mail.Attachments.Add(inline);
return mail;
}
And I also updated the main method to this:
if (sendMessage.Body.Contains("[CompanyLogo]"))
{
sendMessage = EmbedLogo(sendMessage);
}
Make sure your attachments have the Content-ID MIME header and the message's HTML body refers to them using the cid attribute : <img src="cid:xyz"> (where xyz is the value of the Content-ID MIME header).

MailChimp Integaration with MVC 5

I am working on an MVC5 project, the client is interested in using MailChimp for sending emails. I have explored the MailChimp and wrappers ( MailChimp.NET ) and tried in my project as well. I tested the REST API as well and it seems to work , for example; I was able to grab lists and templates using REST API. But, still I am having issues with sending email through MailChimp.
So far, I have tried the following code and its working. Now I want to send an email to a newly registered user. Kindly give me detailed code example that How can I achieve this, because I am totally struck here..
var apiKey = "myapikey-us11";
var listId = "mylistid";
var subscribeRequest = new
{
apikey = apiKey,
id = listId,
email = new
{
email = "muhammad.waqas#seventechnology.co.uk"
},
double_optin = true,
};
var requestJson = JsonConvert.SerializeObject(subscribeRequest);
var reqresult = CallMailChimpApi("lists/", requestJson);
CallMailChimApi
private static string CallMailChimpApi(string method, string requestJson)
{
var endpoint = String.Format("https://{0}.api.mailchimp.com/3.0/{1}", "us11", method);
var wc = new WebClient();
try
{
return wc.UploadString(endpoint, requestJson);
}
catch (WebException we)
{
using (var sr = new StreamReader(we.Response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
I Use this function and it work successfully
public void SendEmailByApiMailChimp ()
{
try
{
string UserEmail = " Exemple#gmail.com ";
MailChimpManager mc = new MailChimpManager("16d***********-us14");
EmailParameter email = new EmailParameter()
{
Email = UserEmail
};
EmailParameter resulte = mc.Subscribe("yourlistnumber", email);
var test = resulte;
}
catch (Exception ex)
{
var ters = ex;
}
}

Exchange EWS get BCC Recipients

I am using EWS to create a StreamingSubscription on an inbox. It is listening for the NewMail event. I am able to pull the From Address, Subject, Body, To Address, CC Address but not the BCC Address. Is there any way to see this list?
CODE:
static void OnEvent(object sender, NotificationEventArgs args)
{
String from = null;
String subject = null;
String body = null;
String to = null;
StreamingSubscription subscription = args.Subscription;
// Loop Through All Item-Related Events
foreach (NotificationEvent notification in args.Events)
{
ItemEvent item = (ItemEvent)notification;
PropertySet propertySet = new PropertySet(ItemSchema.UniqueBody);
propertySet.RequestedBodyType = BodyType.Text;
propertySet.BasePropertySet = BasePropertySet.FirstClassProperties;
// Parse Email
EmailMessage message = EmailMessage.Bind(service, item.ItemId, propertySet);
from = message.From.Address;
subject = message.Subject;
body = message.Body.Text;
if (message.ToRecipients.Count > 0)
{
to = message.ToRecipients[0].Address;
body += "\n TO FIELD";
}
else if (message.CcRecipients.Count > 0)
{
to = message.CcRecipients[0].Address;
body += "\n CC FIELD";
}
/************** Does not work! BccRecipients is always empty *****************/
else if (message.BccRecipients.Count > 0)
{
to = message.BccRecipients[0].Address;
body += "\n BCC FIELD";
}
/************* REST OF CODE ************************/
}
}
That would kind of defeat the point of a blind-carbon-copy. I dont believe it can be done.
Consider using the Journaling feature of Exchange. This uses something called "Envelope Journaling" which includes BCC information for messages within the Exchange environment.
For everything that comes from external sources (gmail) no BCC information is available.
This might help:
http://gsexdev.blogspot.com/2011/06/processing-bccs-in-exchange-transport.html

Categories

Resources