RGdent RGdent - 1 year ago 118
AngularJS Question

Attach Image to email from byte

I am busy trying to understand how to work with images from a

website -> service -> email

What I have done so far is converting the image to
then uploading it to my service. Next I convert it to a byte array and then store it into my database.

At the same time when inserting the byte into my database I want to send the image by attaching it to an email.

At this time the attachment is only a file that I cannot open, so I guess it is just a byte array and not an Image.


public string SendEmail(string send)
TestDb db = new TestDb();

TestImage result = new TestImage();
string[] arData = send.Split('|');

byte[] bytes = new byte[arData[0].Length * sizeof(char)];
System.Buffer.BlockCopy(arData[0].ToCharArray(), 0, bytes, 0, bytes.Length);

result.TestImg = bytes;
result.TestId = int.Parse(arData[1].ToString());


string foto = "name";

Attachment att = new Attachment(new MemoryStream(bytes), foto);

MailMessage mail = new MailMessage();
NetworkCredential cred = new NetworkCredential("Test@gmail.com", "Test123");

mail.Subject = "subject Test";
mail.From = new MailAddress("Test@gmail.com");
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = cred;
return result.Id.ToString();
catch (Exception)



$scope.link = '\img\ionic.png';
var imageData=$base64.encode($scope.link);

$scope.sendimg = function() {

$http.post("http://localhost:53101/TruckService.svc/sendEmail/" + imageData + '|' + 1
.success(function(data) {

.error(function(data) {

Answer Source

I think the problem is with converting image to base64. So check whether you have correct image in imageData by convert it back to an image.

You can use online tools to converto base64 to image Link

So if it's the problem, try to convert your image as below,

function toDataUrl(url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        canvas = null; 
    img.src = url;

toDataUrl('url', function(base64Img){
    // Base64DataURL
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download