Jump to content
Sign in to follow this  
tevez15

[Resolvido] Enviar email por SMTP

Recommended Posts

tevez15

Olá a todos,

Estou a programar uma App para android, estou a usar o eclipse, tenho tentado enviar emails a partir dessa App via SMTP, mas não consigo, dando-me sempre erro.

Estou a testar com o Gmail, a minha conta pessoal, que usando no meu PHP, de outro projeto, funciona sem qualquer problema.

Segui o tut abaixo, mas dá-me sempre erro no envio, e não entendo porque por mais que tente:

http://mobiledevtuts.com/android/android-sdk-smtp-email-tutorial/

Espero que me possam dar umas luzes do que possa estar a falhar. Obrigado

Share this post


Link to post
Share on other sites
tevez15

boa pergunta que me fazes lol

Tenho estado a tentar descobrir.. é quando ele faz este código:

try { 
//m.addAttachment("/sdcard/myPicture.jpg");  // path to file you want to attach
if(m.send()) { 
// success
Toast.makeText(MainActivity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
} else { 
// failure
Toast.makeText(MainActivity.this, "Email was not sent.", Toast.LENGTH_LONG).show(); 
} 
} catch(Exception e) { 
// some other problem
Toast.makeText(MainActivity.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show(); 
}

Ou seja, eu na minha config tenho tudo bem (acho eu, pelo menos está semelhante ao php):

Mail.java


public Mail() { 
_host = "smtp.gmail.com"; // default smtp server 
_port = "465"; // default smtp port 
_sport = "465"; // default socketfactory port 

_user = "diogo.tevez.15/[@]/gmail.com"; // username ps: o @ esta normal no meu codigo
_pass = "pass_do_meu_email"; // password 
_from = "diogo.tevez.15@gmail.com"; // email sent from 
_subject = "Subject text"; // email subject 
_body = "Email content body"; // email body 

_debuggable = true; // debug mode on or off - default off 
_auth = true; // smtp authentication - default on 

_multipart = new MimeMultipart(); 

// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. 
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); 
CommandMap.setDefaultCommandMap(mc); 
} 

Share this post


Link to post
Share on other sites
NunoDinis

O eclipse diz-te onde está a dar erro. Vai aos logs e põe aqui a linha a que ele se refere...


Estranha forma de vida que tem a capacidade de transformar comandos em mensagens de erro.

ndsotware.org

Share this post


Link to post
Share on other sites
tevez15

Sim eu sei.. ele está a mandar isto para fora no erro:

smtp:unknown exception android.os.networkonmainthread

Share this post


Link to post
Share on other sites
bioshock

Procurando um bocado por esse erro no google, uma das possíveis soluções:

NetworkOnMainThreadException:

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

You should call sendfeedback method on asynctask then only above code will work. As webserver is taking lot of time to response main thread becomes unresponsive. To avoid it you should call it on another thread. Hence asynctask is better.

Sendo que deves activar no manifest a ligação à internet.

<uses-permission android:name="android.permission.INTERNET" />

E atendendo ao quote, escrevi à pouco tempo um artigo sobre as AsyncTasks.

  • Vote 1

Share this post


Link to post
Share on other sites
tevez15

Resolvi o problema com isto dentro do oncreate:

super.onCreate(icicle); 
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
setContentView(R.layout.main); 

E a funcionar :)

Obrigado pela ajuda.

Share this post


Link to post
Share on other sites
bioshock

Resolvi o problema com isto dentro do oncreate:

super.onCreate(icicle);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.main); 

E a funcionar :)

Obrigado pela ajuda.

Então trata de retirar isso, porque isso é muito má prática. Basicamente estás a dizer à aplicação para ignorar os erros de thread e continuar a funcionar. Esse código é bom para detectar de onde provém o erro.

(...) StrictMode (android.os.StrictMode) this class can be used to enable and enforce various policies that can be checked for and reported upon. These policies generally include best-practice type coding issues, such as monitoring for actions done on the main thread that shouldn’t be and other naughty or lazy coding practices.

E vai de encontro à minha resposta. Utiliza o AsyncTask ou, se preferires algo mais básico, a função RunOnUiThread(), que deve ser suficiente para o que queres.

runOnUiThread(new Runnable() {
public void run() {
	// O código do SMTP
}
});

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.