android发送邮件初期遇到的问题:
1.发送到QQ邮箱成为垃圾邮件
2.发送到有些邮箱,没有正文
经过几次试验,终于能够正常发送邮件了。
以下是代码:
public
class
MailSender
{
/** * send mail
* @param mailInfo Info
*/
public
boolean
sendMail
(
MailSenderInfo
mailInfo
)
{
// Determine whether authentication
MyAuthenticator
authenticator
;
Properties
pro
=
mailInfo
.
getProperties
();
if
(
mailInfo
.
isValidate
())
{
// Create a password verifier
authenticator
=
new
MyAuthenticator
(
mailInfo
.
getUserName
(),
mailInfo
.
getPassword
());
}
else
{
return
false
;
}
Session
sendMailSession
=
Session
.
getDefaultInstance
(
pro
,
authenticator
);
try
{
Message
mailMessage
=
new
MimeMessage
(
sendMailSession
);
//Create From Address
Address
from
=
new
InternetAddress
(
mailInfo
.
getFromAddress
());
// Set From Address
mailMessage
.
setFrom
(
from
);
// Create To Address
Address
to
=
new
InternetAddress
(
mailInfo
.
getToAddress
());
mailMessage
.
setRecipient
(
Message
.
RecipientType
.
TO
,
to
);
mailMessage
.
setSubject
(
mailInfo
.
getSubject
());
mailMessage
.
setSentDate
(
new
Date
());
String
mailContent
=
mailInfo
.
getContent
();
Multipart
mainPart
=
new
MimeMultipart
();
//create body text
MimeBodyPart
body_text
=
new
MimeBodyPart
();
body_text
.
setText
(
mailContent
);
mainPart
.
addBodyPart
(
body_text
);
//create Attach File
for
(
String
filename:
mailInfo
.
getAttachFileNames
()){
FileDataSource
fileDataSource
=
new
FileDataSource
(
new
File
(
filename
));
DataHandler
dataHandler
=
new
DataHandler
(
fileDataSource
);
MimeBodyPart
mimeBodyPart
=
new
MimeBodyPart
();
mimeBodyPart
.
setDataHandler
(
dataHandler
);
try
{
String
fileNameNew
=
MimeUtility
.
encodeText
(
fileDataSource
.
getName
(),
"utf-8"
,
null
);
mimeBodyPart
.
setFileName
(
fileNameNew
);
}
catch
(
UnsupportedEncodingException
e
)
{
e
.
printStackTrace
();
mimeBodyPart
.
setFileName
(
fileDataSource
.
getName
());
}
mimeBodyPart
.
setText
(
mailInfo
.
getContent
());
mainPart
.
addBodyPart
(
mimeBodyPart
);
mailMessage
.
setContent
(
mainPart
);
}
mailMessage
.
saveChanges
();
// send email
Transport
.
send
(
mailMessage
);
return
true
;
}
catch
(
MessagingException
ex
)
{
ex
.
printStackTrace
();
}
return
false
;
}
class
MyAuthenticator
extends
Authenticator
{
String
userName
=
null
;
String
password
=
null
;
public
MyAuthenticator
(
String
username
,
String
password
)
{
this
.
userName
=
username
;
this
.
password
=
password
;
}
protected
PasswordAuthentication
getPasswordAuthentication
(){
return
new
PasswordAuthentication
(
userName
,
password
);
}
}
}