Groovy MailService getting source code of sent email - email

I am using Groovy mailService for sending emails.
For logging purpose I want to get the plain text of the email sended (like you can see in an email programm).
Code:
mailService.sendMail {
async true
to mTo
subject mSubject
from mFrom
html outFile.getText()
}
Is it possible to get the generated mail?
Best regards,
Peter

Found a simple solution:
MimeMailMessage mailret = mailService.sendMail {
multipart true
async true
to mTo
subject mSubject
from mFrom
html mBody
attachBytes filename, filetype, outFile.getBytes()
}
mailret.mimeMessage.writeTo(System.out)

You can simulate what the service internally does by (do this in a service or somewhere available for Spring processing):
MailMessageBuilderFactory mailMessageBuilderFactory
GrailsApplication grailsApplication
...
def getMessage () {
Closure callable = {
async true
to mTo
subject mSubject
from mFrom
html outFile.getText()
}
MailMessageBuilder messageBuilder = mailMessageBuilderFactory.createBuilder(grailsApplication.config.grails.mail)
callable.delegate = messageBuilder
callable.resolveStrategy = Closure.DELEGATE_FIRST
callable.call(messageBuilder)
println messageBuilder.message // (your 'MailMessage' message printed out here)
}
For more see http://docs.spring.io/spring-framework/docs/2.0.x/api/org/springframework/mail/MailMessage.html

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.

Error empty content gmail using javamail api send email smtp

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).

Grails injected Mail Service bean is null inside a controller

I am trying to use the following Grails Mail plugin: https://grails.org/plugin/mail
I've added the depedency in BuildConfig.groovy:
plugins {
//mail plugin
compile "org.grails.plugins:mail:1.0.7"
}
The I've configured it to use a specific email by adding the following code in Config.groovy:
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "-my email-"
password = "-my password-"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
from = "no-reply#kunega.com"
}
}
I have a controller where I declare the mailService so it should be injectd as a bean:
#Secured("permitAll")
class RegisterController {
def mailService
def springSecurityService
#Transactional
def registerAccount(UserCommand userCommand) {
def model
if (springSecurityService.isLoggedIn()) {
model = [success: false, message: 'Log out to register a new account.']
response.status = 400
} else if (userCommand.validate()) {
User u = userCommand.createUser()
u.save(flush: true);
Role role = Role.findByAuthority("ROLE_USER")
UserRole.create u, role, true
def link = createLink(controller: 'register', action: 'activateAccount', params: [code: u.confirmCode])
mailService.sendMail {
async true
to 'kunega#mailinator.com'
html "Activate your account on Kunega"
}
model = [success: true, message: 'An activation link has been sent to your email.']
response.status = 201
} else {
model = [success: false, errors: userCommand.getErrors()]
response.status = 400
}
render model as JSON
}
}
I am trying to use the sendMail method it in the registerAccount method of the controller. However I get an error, which basically says that the mailService object is null. Here is the error message:
errors.GrailsExceptionResolver NullPointerException occurred when processing request: [POST] /Kunega/register/createAccount
Cannot invoke method $() on null object. Stacktrace follows:
java.lang.NullPointerException: Cannot invoke method $() on null object
at com.kunega.RegisterController$_$tt__registerAccount_closure2.doCall(RegisterController.groovy:32)
at grails.plugin.mail.MailService.sendMail(MailService.groovy:53)
at grails.plugin.mail.MailService.sendMail(MailService.groovy:59)
at com.kunega.RegisterController.$tt__registerAccount(RegisterController.groovy:29)
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:198)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter.doFilter(GrailsAnonymousAuthenticationFilter.java:53)
at grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter.doFilter(RequestHolderAuthenticationFilter.java:49)
at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.java:82)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
And there is another strange thing that I should mention. I'm using IntelliJ Ultimate Edition, and here is a curios thing:
If you notice inside the highlighted area with red, the IDE is showing that it can't recognize the arguments inside the closure that is passed to sendEmail.
I've never used this plugin before, so I just followed the steps in the docs, but apparently something is wrong. Thank you for your help.
In your code you have:
html "Activate your account on Kunega"
which I suppose should be either:
html "Activate your account on Kunega"
or
html "Activate your account on Kunega"
otherwise you call a method html with params "Activate your account on Kunega".

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.