Error empty content gmail using javamail api send email smtp - email

I'm working project : jsf, richfaces. I has just updated javamail api newest version 1.5.5 at https://java.net/projects/javamail/pages/Home
When i test send email from gmail to my gmail,
Subject : Subject test.
Content : Content test. And config : smtp.gmail.com, 465, SSL.
It has just subject and no content in my inbox receive gmail :
And log :
And my code :
try {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Set the host smtp address
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.ssl.trust", "*");
props.put("mail.smtp.ssl.socketFactory", sf);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
.......
.......
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setText("UTF8");
// set the from and to address
InternetAddress addressFrom = new InternetAddress(SMTP_AUTH_USER);
msg.setFrom(addressFrom);
System.out.println(addressFrom);
msg.setSubject(subject, "utf-8");
......
......
try {
String content = replaceCharacterInEmail(cus, null,null, message);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent(content, "text/html; charset=utf-8");
// attach the file to the message
Multipart mp = new MimeMultipart();
int count = 0;
if(files != null){
while (count < files.size()) {
MimeBodyPart mbdp = new MimeBodyPart();
mbdp.attachFile(files.get(count));
mp.addBodyPart(mbdp);
count++;
}
}
// create the Multipart and add its parts to it
mp.addBodyPart(mbp1);
// add the Multipart to the message
msg.setContent(mp);
Transport.send(msg);
} catch (Exception e) {
invalidAddress += (", " + address.trim());
e.printStackTrace();
}finally{
if (!"".equals(emailFails)) {
emailFails = emailFails.substring(1);
}
}
But, when i test above code at another project test (java application) with above lib javamail. It's ok :
.
I don't think problem at version of lib javamail. I don't know different between 2 project, because part send email is similar. How can i fix that error ?

Please observe this email structure:
-- multipart/mixed
-- mutlipart/alternative
-- text/plain
-- text/html
-- application/octet-stream (or any other mimetypes)

I found problem is conflict library at lib of jboss server and lib of app.ear (deploy).

Related

Xamarin, get error sending mail using SmtpClient

I am using System.Net.Mail.SmtpClient to send mail in my Xamarin Form app. It's set to using my gmail address, and working great.
I would like to get the error from the smtp server (if there is one) to inform the user.
So, I am using the event _SendCompleted
Here my code
(sending email)
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(outils.emailEmetteur);
mail.To.Add("toto#outlook.frfr");//Tiers.contactEmail);
mail.Subject = outils.emailObjetDefaut;
mail.Body = outils.emailMessageDefaut;
bool fileExist = File.Exists(filePath);
if (fileExist)
{
Attachment pJ = new Attachment(filePath);
mail.Attachments.Add(pJ);
smtpServer.Port = 587;
smtpServer.Host = "smtp.gmail.com";
smtpServer.EnableSsl = true;
smtpServer.UseDefaultCredentials = false;
smtpServer.Credentials = new NetworkCredential(outils.emailEmetteur, outils.emailEmetteurMDP);
try
{
smtpServer.SendAsync(mail, null);
smtpServer.SendCompleted += smtpServer_SendCompleted;
return true;
}
catch (Exception ex)
{
}
}
(send completed event)
private static void smtpServer_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
string token = (string)e.UserState;
string info = "";
if (e.Cancelled)
{
info = "Send canceled.";
}
if (e.Error != null)
{
info = e.Error.ToString();
}
else
{
info = "Message sent.";
}
}
I am trying to send an email to an incorrect address (toto#outlook.frfr)
My event is correctly triggered, but e.Cancelled and e.Error are NULL, and, in my Gmail inbox, I receive an error from smtp server telling me that the email address was incorrect, and that what I want to get in my Xamarin app.
Do you have any idea ? Thanks :)
Your client relays it to Gmail's outgoing mail server; the transaction to submit the message to SMTP is successful. The error only happens later, when Gmail tries to connect to the recipient's mail server, and can't resolve it; at that point, your client is no longer necessarily connected, and so the mail server generates a bounce message and delivers it to the sender's inbox.
In the general case, you either have to write your own mail server (but no, don't go there) or examine the inbox for bounce messages.

Jmeter Groovy JavaMail API multipart add content to sample result

Looking at answers posted in Reading Emails based on recipient email id in Jmeter using groovy I actually managed to use the recipient search term.
Using the below in a JSR223 Sampler
import javax.mail.Multipart
import javax.mail.internet.MimeMultipart
import javax.mail.Message
import javax.mail.search.RecipientStringTerm
Properties properties = new Properties()
properties.put('mail.imap.host', 'your mail server host') // i.e. imap.gmail.com
properties.put('mail.imap.port', your mail server port) // i.e. 993
properties.setProperty('mail.imap.socketFactory.class', 'javax.net.ssl.SSLSocketFactory')
properties.setProperty('mail.imap.socketFactory.fallback', 'false')
properties.setProperty('mail.imap.socketFactory.port', 'your_mail_server_port') // i.e. 993
def session = javax.mail.Session.getDefaultInstance(properties)
def store = session.getStore('imap')
store.connect('your username (usually email address)', 'your_password')
def inbox = store.getFolder('INBOX')
inbox.open(javax.mail.Folder.READ_ONLY)
def onlyToGivenUser = inbox.search(new RecipientStringTerm(Message.RecipientType.TO,'your_recipient_address')) // i.e. test+1#gmail.com
onlyFromGivenUser.each { message ->
if (message.getContent() instanceof Multipart) {
StringBuilder content = new StringBuilder()
def multipart = (Multipart) message.getContent()
multipart.eachWithIndex { Multipart entry, int i ->
def part = entry.getBodyPart(i)
if (part.isMimeType('text/plain')) {
content.append(part.getContent().toString())
}
}
SampleResult.setResponseData(content.toString(), 'UTF-8')
} else {
SampleResult.setResponseData(message.getContent().toString(), 'UTF-8')
}
}
This works perfectly, but fails when email is ContentType: multipart/MIXED as it does not drill down to multipart/RELATED, multipart/ALTERNATIVE and then to TEXT/PLAIN or TEXT/HTML, on which I like to do a regex on to extract a link from the body.
Guessing some counter on i is needed and an "if else", or something like mentioned here, but unsure how to convert to fit in the above script...
Any help would be much appreciated.
I stepped away from javax.mail.Multipart and javax.mail.internet.MimeMultipart and have implemented the below code in a While Controller
import javax.mail.Message
import javax.mail.search.RecipientStringTerm
Properties properties = new Properties();
properties.put('mail.imap.host', 'your mail server host') // i.e. imap.gmail.com
properties.put('mail.imap.port', your mail server port) // i.e. 993
properties.setProperty('mail.imap.socketFactory.class', 'javax.net.ssl.SSLSocketFactory')
properties.setProperty('mail.imap.socketFactory.fallback', 'false')
properties.setProperty('mail.imap.socketFactory.port', 'your_mail_server_port') // i.e. 993
def session = javax.mail.Session.getDefaultInstance(properties)
def store = session.getStore('imap')
store.connect('your username (usually email address)', 'your_password')
def inbox = store.getFolder('INBOX');
inbox.open(javax.mail.Folder.READ_ONLY);
def onlyToGivenUser = inbox.search(new RecipientStringTerm(Message.RecipientType.TO,'your_recipient_address')); // i.e. test+1#gmail.com
try {
onlyToGivenUser.each { message ->
ByteArrayOutputStream emailRaw = new ByteArrayOutputStream();
message.writeTo(emailRaw);
SampleResult.setResponseData(emailRaw.toString(), 'UTF-8');
}
} catch (Exception ex) {
log.warn("Something went wrong", ex);
throw ex;
}
Hope this helps someone one day.

Unable to send more than 5 emails to Exchange server using JavaMail

I have a method that sends many emails to exchange server over smtp using JavaMail, below is my code,
public void sendMail(){
final String host="host",port="587",username="mail1#local.local",password="password",from="";
try {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.ssl.trust", host);
final String email = from;
Authenticator authenticator = new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
};
Session session = Session.getInstance(props,authenticator);
InternetAddress replyToAddress [] = new InternetAddress[1];
replyToAddress[0] = new InternetAddress("mail1#local.local");
Transport transport = session.getTransport("smtp");
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress("mail1#local.local"));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("mail2#local.local"));
mimeMessage.setSubject("Test");
mimeMessage.setText("Hello Testing");
mimeMessage.setReplyTo(replyToAddress);
transport.send(mimeMessage);
System.out.println("Email has been Sent Successfully to");
} catch (MessagingException e) {
e.printStackTrace();
}
Now when I apply a loop and call this function 10 times then only first five emails are sent successfully, for rest of the request I get the following exception,
javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
java.net.SocketException: Connection closed by remote host
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2157)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2144)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1210)
at javax.mail.Transport.send0(Transport.java:197)
at javax.mail.Transport.send(Transport.java:124)
if I increase the request count then still only first five emails are sent, rest of them throws the exception.
If I put the failed request in some queue and retry them later then some of them will be sent.
Any clue will be appreciated, do I need to check for some configuration on Exchange server?
We have seen this exact same issue with a MS Exchange Server 2010. We had to increase the ReceiveConnector message rate limit by issuing the following Powershell-command:
Set-ReceiveConnector "Client CLIENTNAME" -MessageRateLimit unlimited

Can't upload file to Google Drive from service account

I am trying to upload a file to google drive using google service account.
Driver Service
public static Drive getDriveService(String secretKeyFile) throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(DriveScopes.DRIVE)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(secretKeyFile))
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).setApplicationName("appl name").build();
return service;
}
Insert File
private static File insertFile(Drive service, String title, String description,String mimeType, String filename) {
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
Main Method
Drive service=null;
try {
String secretFile= "somedigit-privatekey.p12";
service = getDriveService(secretFile);
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
File insertFile = insertFile(service, "test title", "File description", "text/plain", "c:\\test.txt");
List list = service.files().list();
System.out.println("Files Id : "+insertFile.getId());
System.out.println("Count Files : "+list.size());
Now, my questions is :
How and where can i check that file was uploaded?
Why it returns the file ID but list.size() is zero.
It returns the download link also but when i paste that link in
browser it doesn't download any file.
You are creating a listing request but not executing it. Use execute method to make the request:
service.files().list().execute();
If you paste the download link into the browser, it will respond with 401, because your download request should also contain a valid Authorization header. Use the following snippet to download the file programmatically.
HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
InputStream stream = resp.getContent();
stream is an input stream for the file content.
Or add an Authorization: Bearer <access token> to the request you're making elsewhere.

Writing an encrypted mail via Exchange Web Services

I would like to send an encrypted EMail Message with Exchange WEb Services using C#.
Is there any possibillity?
Thanks
Edit:
My Mail body encrypter:
public static byte[] encry(string body, ContentTyp typ, string to )
{
X509Certificate2 cert = GetMailCertificate(to);
StringBuilder msg = new StringBuilder();
msg.AppendLine(string.Format("Content-Type: text/{0}; charset=\"iso-8859-1\"", typ.ToString()));
msg.AppendLine("Content-Transfer-Encoding: 7bit");
msg.AppendLine();
msg.AppendLine(body);
EnvelopedCms envelope = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(msg.ToString())));
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
envelope.Encrypt(recipient);
//System.IO.MemoryStream ms = new System.IO.MemoryStream(envelope.Encode());
return envelope.Encode();
}
Main
byte [] con = encrypted.encry("test", encrypted.ContentTyp.plain, "test#server.com");
EmailMessage msg1 = new EmailMessage(_server);
msg1.MimeContent = new MimeContent("UTF-8", con);
msg1.ToRecipients.Add("user#server.com");
msg1.InternetMessageHeaders = ??
msg1.Send();
If you are referring to S/Mime encryption, then you'll have to create the encrypted message according to RFC 3852 and RFC 4134. After you've done that, you can send the message.
Using the EWS Managed API, this can be done as follows:
var item = new EmailMessage(service);
item.MimeContent = new MimeContent(Encoding.ASCII.HeaderName, content);
// Set recipient infos, etc.
item.Send();
EDIT:
You should add the standard headers like From, To, Date, Subject, etc. And the content-type.
Subject: Test
From: "sender" <sender#yourcompany.com>
To: "recipient" <recipient#othercompany.com>
Content-Type: application/pkcs7-mime; smime-type=signed-data; name=smime.p7m
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=smime.p7m
Your encrypted body goes here
Just use a StringWriter put all that together. The result is your MIME body.